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