![](/img/trans.png)
[英]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.