查找包含给定文件(Python)字符串的文件夹中的所有文件
我有一个包含很多文件的文件夹,其中一些包含一个或多个关键字,我还有一个单独的文件,仅包含关键字,每行一个单词,如下所示:查找包含给定文件(Python)字符串的文件夹中的所有文件,python,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: pri
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()
但它不起作用,因为我只收到负面结果。我如何修复它?我认为最好的模块是。您可以简单地从文件中读取关键字,并获得与关键字匹配的文件列表 注意未测试。我建议你自己做。这只是一个帮助/概述
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():
什么都没变,抱歉,奇怪。我已经验证它解决了我系统上的问题。这可能只是示例中的问题,但请注意缩进