对于在 os 步行期间已删除的文件的循环抛出异常

For loop throwing exception on file already deleted during os walk

我正在编写一个脚本,遍历目录并查找具有典型 Windows 安装程序扩展名的文件并将其删除。当我 运行 使用列表(与检查 .msi 或 .exe 相比)时,它会在再次通过嵌套循环时中断。似乎它 运行s 通过我的列表,删除一种类型的扩展然后 运行s 再次通过循环并尝试找到相同的扩展然后抛出异常。这是我简单打印但不删除文件时的输出:

> C:\Users\User\Documents\Python Scripts>python test.py < test_run.txt
> Found directory: . Found directory: .\test_files
>          Deleting test.cub
>          Deleting test.idt
>          Deleting test.idt
>          Deleting test.msi
>          Deleting test.msm
>          Deleting test.msp
>          Deleting test.mst
>          Deleting test.pcp
>          Deleting test1.exe

当我尝试用 os.remove 运行 它时,它给出以下内容:

Found directory: .
Found directory: .\test_files
         Deleting test.cub
Traceback (most recent call last):
  File "test.py", line 13, in <module>
    os.remove(fileName)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'test.cub'

我阅读了 os walk 并且它似乎工作正常,我似乎无法弄清楚这个脚本哪里出了问题。代码如下:

import os

myList = [".msi", ".msm", ".msp", ".mst", ".idt", ".idt", ".cub", ".pcp", ".exe"]


rootDir = '.'
for dirName, subdrList, fileList in os.walk(rootDir):
    print('Found directory: %s' %dirName)
    for fileName in fileList:
        for extName in myList:
            if(fileName.endswith(extName)):
                    print('\t Deleting %s' % fileName)
                    os.remove(fileName)

文件 test.cub 的正确相对名称是 .\test_files\test.cub

您提供的相对名称是 .\test.cub

正如 os.walk documentation 中所说:

To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name).