在一个文件夹中包含许多文本文件。如何在这些文件中找到搜索词(例如,某些词)以获得该搜索词所在文档的名称和路径文件?
我尝试了建议的修改方法,但它只显示文件夹中的第一个文件,而不是搜索术语:
dirname = '/Users/user/Documents/DataText/'
search_terms = ['elevator']
for f in os.listdir(dirname):
text = open(os.path.join(dirname,f))
text = [line.rstrip('\n') for line in f]
if any([term in text for term in search_terms]):
print (f)
答案 0 :(得分:1)
import os
dirname = '/home/user/mydirectory'
search_terms = ['apple', 'banana', 'peach']
for f in os.listdir(dirname):
text = '\n'.join( open(os.path.join(dirname,f)).readlines() )
if any([term in text for term in search_terms]):
print f