[英]Find files in a directory containing desired string in Python file and stored all that files into another folder
[英]Find all files in folder containing strings from given file (Python)
我有一个包含很多文件的文件夹,其中一些包含一个或几个关键字,我还有一个单独的文件,仅包含关键字,每行一个单词,如下所示:
keyword1
keyword2
keyword3
我需要找到所有这些文件。
所以我有这段代码
import os
directory = os.listdir("D:/where_2_search")
with open('what_2search.txt','r') as searchlist:
for line in searchlist:
print(line)
for fname in directory:
if os.path.isfile("D:/where_2_search" + os.sep + fname):
searchedfile = open("D:/where_2_search" + os.sep + fname, 'r')
if line in searchedfile.read():
print('found string in file %s' % fname)
else:
print('string not found')
searchedfile.close()
但这不起作用,因为我仅收到负面结果。 我该如何解决?
我认为最好的模块是glob 。 您可以简单地从文件中读取关键字并获取与关键字匹配的文件列表。
注意未经测试。 我建议你自己做。 这只是一个帮助/概述。
from glob import glob
import os
with open('what_2search.txt','r') as searchlist:
keywords= searchlist
found_files = []
# You might want to change the working directory as follow if needed
os.chdir(path_where_those_files_are)
for keyword in keywords:
found_files.append(glob(keyword)) # Here is a little bug. But can easily sort this out
print(found_files) # List of files needed
关键字末尾有换行符
尝试更改为此
if line.rstrip() in searchedfile.read():
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.