我编写的脚本遍历目录并查找具有典型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 <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)
答案 0 :(得分:1)
文件test.cub
的正确相对名称为.\test_files\test.cub
。
您提供的相对名称是.\test.cub
。
正如os.walk documentation中所述:
获取完整路径(以 top 开头)到文件或目录中 dirpath ,执行
os.path.join(dirpath, name)
。