私は、テキスト文字列の検索を解析するのに必要な数百のログファイルを持っています。私ができるようにしたいのは、現在のフォルダ内のすべてのファイルを開いて解析し、その結果をoriginal_name_parsed_log_file.txtという新しいファイルに記録するPythonスクリプトを実行することです。私はスクリプトが1つのファイルで作業していましたが、今はディレクトリ内のすべてのファイルを実行する際にいくつかの問題があります。ログを解析して特定のテキスト文字列を含む行を抽出する方法は?
以下は私がこれまで行ってきたことですが、atmで動作していません。最初のデフを無視して...私はフォントの色を変えて遊んでいた。
import os
import string
from ctypes import *
title = ' Log Parser '
windll.Kernel32.GetStdHandle.restype = c_ulong
h = windll.Kernel32.GetStdHandle(c_ulong(0xfffffff5))
def display_title_bar():
windll.Kernel32.SetConsoleTextAttribute(h, 14)
print '\n'
print '*' * 75 + '\n'
windll.Kernel32.SetConsoleTextAttribute(h, 13)
print title.center(75, ' ')
windll.Kernel32.SetConsoleTextAttribute(h, 14)
print '\n' + '*' * 75 + '\n'
windll.Kernel32.SetConsoleTextAttribute(h, 11)
def parse_files(search):
for filename in os.listdir(os.getcwd()):
newname=join(filename, '0_Parsed_Log_File.txt')
with open(filename) as read:
read.seek(0)
# Search line for values if found append line with spaces replaced by tabs to new file.
with open(newname, 'ab') as write:
for line in read:
for val in search:
if val in line:
write.write(line.replace(' ', '\t'))
line = line[5:]
read.close()
write.close()
print'\n\n'+'Parsing Complete.'
windll.Kernel32.SetConsoleTextAttribute(h, 15)
display_title_bar()
search = raw_input('Please enter search terms separated by commas: ').split(',')
parse_files(search)
最も簡単な方法は、接合すべき文字列のリストを必要とする文字列の方法であります名前ワイルドカード文字列を照合してディレクトリ内にあるファイルは、組み込みの 'glob'モジュールを使用することです。 – PaulMcG