2

I'm trying to write a script that will automatically delete all the temp files in a specific folder, and I noticed that this script also deletes all the text files in that folder as well. Can anyone explain why it does that?

   import os
   path = 'C:\scripts27'
   for root, dirs, files in os.walk(path):
       for currentFile in files:
           print "processing file: " + currentFile
           extensions=('.tmp')
           if any(currentFile.lower().endswith(ext) for ext in extensions):
               os.remove(os.path.join(root, currentFile))

I'm running this script using Python 2.7.10 on a Windows 8.1 PC 64-bit.

Thanks!

4

1 回答 1

7

我假设您的意思是提供扩展列表。但在您的情况下,extensions定义为('.tmp')which不是元组而是字符串。这会导致您的代码遍历所有文件并检查以 , 结尾的名称,.从而删除您的文件。tmp.txt

这里的解决方法是将扩展定义为['.tmp']or ('.tmp',)(注意尾随,)。

于 2015-09-04T22:25:00.757 回答