Directory recursion only goes one directory deep

Viewed 30

I'm making a script in Python to remove all leftover .exe files from compiling stuff:

import os

main_dir = '../RemoveExes'


def remove_all_in_dir(path):
    print(f'Currently in {path}. Listdir:', os.listdir(path))
    for current_name in os.listdir(path):
        if os.path.isdir(current_name):
            print(f'{path}/{current_name} is a directory. Entering')
            remove_all_in_dir(f'{path}/{current_name}')
        elif current_name.endswith('.exe'):
            print(f'Would remove: {current_name}')
        else:
            print(f'{current_name} is not an .exe or a directory. Omitting.')


remove_all_in_dir(main_dir)

../RemoveExes is a directory with the following structure:

 RemoveExes
 ├  bar
 │  ├  subdir
 │  │  ├ bulb.exe
 │  │  └ some_text.txt
 │  ├ doc.docs
 │  └ een.jpg
 ├  foo
 │  ├ exe.exe
 │  └ txt.txt
 ├ cleanup.py
 ├ prog.exe
 ├ script.py
 └ text.txt

The program successfully "removes" exe.exe (1 directory deep) and prog.exe (0 directories deep), but does not touch bulb.exe (2 directories deep). Is this to limit recursion in Python, or am I doing something wrong?

1 Answers

os.listdir returns a list of file names only, without the directory names, so you should join the directory names with the file names to form the full path names instead:

def remove_all_in_dir(path):
    print(f'Currently in {path}. Listdir:', os.listdir(path))
    for current_name in os.listdir(path):
        full_path = os.path.join(path, current_name)
        if os.path.isdir(full_path):
            print(f'{full_path} is a directory. Entering')
            remove_all_in_dir(f'{full_path}')
        elif current_name.endswith('.exe'):
            print(f'Would remove: {full_path}')
        else:
            print(f'{full_path} is not an .exe or a directory. Omitting.')
Related