关于python:对于在os walk期间已经删除的文件上的循环抛出异常

For loop throwing exception on file already deleted during os walk

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

1
2
3
4
5
6
7
8
9
10
11
> 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运行它时,它给出了以下信息:

1
2
3
4
5
6
7
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'

我在OSWalk上读到了,它似乎工作正常,我似乎不知道这个脚本哪里出错了。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
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文档中所说:

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