简体   繁体   中英

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.

shutil.rmtree deletes an entire directory tree .

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

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))]

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM