2013-04-10 89 views
0
import os 
folder = 'C:/Python27/Data' 
for the_file in os.listdir(folder): 
    file_path = os.path.join(folder, the_file) 
    try: 
     if os.path.isfile(file_path): 
      os.unlink(file_path) 
    except Exception, e: 
     print e 

这是我用来从目录中删除文本文件的代码,但是我想删除特定文件,并根据某些关键字对它们进行过滤。 如果文本文件不包含单词“dollar”,则将其从文件夹中删除。这应该为目录内的所有文件完成。删除特定文本文件

+1

只是为了确保:你的意思是,*文件*包含单词,而不是* *文件名?另外,看起来你的代码会比文本文件更多地删除... – 2013-04-10 12:59:36

+0

@TimPietzcker是的,如果它不包含'单词',单词可能像这样的'dollar056'或'dollar12112ab'等,如果它有没有像这样的词,比它应该删除文本文件 – Rocket 2013-04-10 13:02:39

回答

2

如果文件比较小,那么下面这个简单的解决办法是充分的:

if os.path.isfile(file_path): # or some other condition 
    delete = True    # Standard action: delete 
    try: 
     with open(file_path) as infile: 
      if "dollar" in infile.read(): # don't delete if "dollar" is found 
       delete = False 
    except IOError: 
     print("Could not access file {}".format(file_path)) 
    if delete: 
     os.unlink(file_path) 

如果文件非常大,你不想完全加载它们到内存中(特别是如果你希望在该文件中早期出现的搜索文本),用以下内容替换上述with块:

 with open(file_path) as infile: 
      for line in file: 
       if "dollar" in line: 
        delete = False 
        break 
+0

你可以通过不使用'os.path.isfile()'来过滤文件来改进这个解决方案,但是例如使用一组已知的扩展名,如'.txt','.md'等。 – whatyouhide 2013-04-10 13:10:58

+0

@whatyouhide:当然(这就是为什么我评论这个问题)。也许有问题的目录只包含文本文件... – 2013-04-10 13:12:18

相关问题