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”,则将其从文件夹中删除。应该对目录中的所有文件执行此操作。

4

1 回答 1

2

If the files are rather small, then the following simple solution would be adequate:

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)

If the files are very large and you don't want to load them entirely into memory (especially if you expect that search text to occur early in the file), replace the above with block with the following:

        with open(file_path) as infile:
            for line in file:
                if "dollar" in line:
                    delete = False
                    break
于 2013-04-10T13:08:20.907 回答