[英]Python Text Searching in .txt files in different folders with printing the name of file and folder
I'm making a script in Python for searching for the selected term (word/couple words, sentence) in a bunch of .txt files in a selected folder with printing out the names of the .txt files which contain the selected term. 我正在用Python编写脚本,以在选定文件夹中的一堆.txt文件中搜索选定的术语(单词/成对单词,句子),并打印出包含选定术语的.txt文件的名称。 Currently is working pretty fine using os
module: 当前使用os
模块可以正常工作:
import os
dirname = '/Users/User/Documents/test/reports'
search_terms = ['Pressure']
search_terms = [x.lower() for x in search_terms]
for f in os.listdir(dirname):
with open(os.path.join(dirname,f), "r", encoding="latin-1") as infile:
text = infile.read()
if all(term in text for term in search_terms):
print (f)
But I wanna make the extension for the script: to be able to search not only in one folder (dirname), but in two for example (dirname1, dirname2) which consist of also .txt files. 但是我想对脚本进行扩展:不仅可以在一个文件夹(目录名)中搜索,而且还可以在两个目录(目录名,目录名2)中搜索,其中还包括.txt文件。 Also I would like to print not only the name of the searched report but the name of the directory (dirname) where it locates. 另外,我不仅要打印搜索到的报告的名称,还要打印它所位于的目录(目录名)的名称。 Is it possible to do that using os
module or there will be some other approaches to do that? 是否可以使用os
模块来做到这一点,或者还有其他方法可以做到这一点?
You can iterate over dirnames like this : 您可以像这样遍历目录名:
import os
dirnames = ['/Users/User/Documents/test/reports','/Users/User/Documents/test/reports2']
search_terms = ['Pressure']
search_terms = [x.lower() for x in search_terms]
for dir_name in dirnames:
for f in os.listdir(dir_name):
with open(os.path.join(dir_name, f), "r", encoding="latin-1") as infile:
text = infile.read()
if all(term in text for term in search_terms):
print("{} in {} directory".format(f, dir_name))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.