ARichLlama
ARichLlama

Reputation: 5

Why is os.listdir showing to a file while I set it to the directory?

So, I am making a python project that deletes files in a directory and my code is:

    tmp_dir = r"C:\Users\User\AppData\Roaming\Microsoft\Teams\tmp"
    tmp_list = os.listdir(tmp_dir)

    for tmp_files in tmp_list:
        shutil.rmtree(os.path.join(tmp_dir, tmp_files))

and I am getting the following error:

Traceback (most recent call last): File "<my program's location>", line 9, in shutil.rmtree(os.path.join(tmp_dir, tmp_files)) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\shutil.py", line 737, in rmtree return _rmtree_unsafe(path, onerror) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\shutil.py", line 596, in _rmtree_unsafe onerror(os.scandir, path, sys.exc_info()) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\shutil.py", line 593, in _rmtree_unsafe with os.scandir(path) as scandir_it: NotADirectoryError: [WinError 267] The directory name is invalid: 'C:\Users\User\AppData\Roaming\Microsoft\Teams\tmp\x64.json'

Process finished with exit code 1

Can you please tell me what is wrong in my code? Any help is appreciated.

Upvotes: 0

Views: 952

Answers (3)

crissal
crissal

Reputation: 2647

shutil.rmtree deletes an entire directory tree.

To remove a single file, you can use os.remove.

Upvotes: 2

frakod
frakod

Reputation: 1871

os.listdir lists both files and folders

That rmtree you are doing only works on folders

So when the iterations reaches a file, it gives error

For both folders and files you need to do something like this

for temp_files in temp_list :
    if temp_files.isdir():
        shutil.rmtree(os.path.join(tmp_dir, tmp_files))
    else :
        os.remove("file path/filename")

Upvotes: 0

jonathan
jonathan

Reputation: 269

os.listdir returns all the files and directories in the path given. If you want to remove all the dirs you can filter by using os.path.isdir and then remove just directories.

You can try this code for getting all directories in a given folder:

tmp_list = [d for d in os.listdir(tmp_dir) if os.path.isdir(os.path.join(tmp_dir, d))]

Upvotes: 0

Related Questions