为什么 os.listdir 显示在文件中,而我将其设置为目录?

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

所以,我正在制作一个 python 项目,用于删除目录中的文件和我的 代码是:

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

我收到以下错误:

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

你能告诉我我的代码有什么问题吗?感谢任何帮助。

shutil.rmtree deletes an entire directory tree.

要删除单个文件,您可以使用os.remove

os.listdir returns 给定路径中的所有文件和目录。如果要删除所有目录,可以使用 os.path.isdir 进行过滤,然后仅删除目录。

您可以尝试使用此代码获取给定文件夹中的所有目录:

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

os.listdir 列出文件和文件夹

您正在执行的 rmtree 仅适用于文件夹

所以当迭代到达一个文件时,它给出错误

对于文件夹和文件,您需要执行类似的操作

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