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",则将其从文件夹中删除。这应该对目录中的所有文件完成。
答案 0 :(得分: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