私は、.logファイルを検索し、キーワード "Complete Respons"を見つけるプログラムを作成しています。見つかったすべてのキーワードは、後で記述して新しい.txtファイルに保存する必要があります。私は今、その時点で1つのドキュメントを検索するプログラムを管理していますが、同じディレクトリに同じtypの+50のドキュメントを持っています。これは、同時にすべてを検索し、同じ.txtドキュメント。私は本当にいくつかの助けを使うことができました...!次に、ループの中で、あなたの関数を呼び出すpython - キーワード検索プログラム
with open('CompleteResponse.txt', 'a') as file_handler:
:
import glob
for filename in glob.glob('C:\Users\\Documents\read_log_files\*.log'):
read_log_file(filename, 'Complete Response:')
はやるべき おかげ
def read_log_file(filename, keyword): #file
saved_word = [] # Array
# read file
with open(filename) as file_search: #open search file
file_search = file_search.readlines() #read file
for lines in file_search: # every word is scaned
if keyword in lines: # extract the keyword
saved_word.append(lines) #store all found keywords in array
# write in new file
with open('CompleteResponse.txt', 'w') as file_handler:
file_handler.write(f"{filename}\n")
for i in range(len(saved_word)):
file_handler.write(f"{saved_word[i]}")
print('done') # completed
print(len(saved_word)) # count found words
read_log_file(r'C:\Users\\Documents\read_log_files\test.log', 'Complete Response:')
してください詳しく質問:あなたが問題を抱えているのですか?例外? – pinturic
@fili:@ Shaiによって与えられた答えがあなたに届きます。あなたのコードに関するちょっとしたコメント: 'for file_search' - 複数の理由は? 'for line in file_search'を実行すると' file_search = file_search.readlines() 'の習慣に入りません。これは' file_search'のタイプを変更し、微妙なバグにつながる可能性があります。最後に、 'file_search'と' file_handler'は奇妙な名前です。そして、ログファイルが大きくなるにつれて、それらをすべて配列に読み込まず、行ごとに処理するのを避けたいかもしれません。 –