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