[英]Parse Specific Text File to CSV Format with Headers
我有一個每幾毫秒更新一次的日志文件,但是當前使用四(4)個不同的定界符保存該信息。 日志文件包含數百萬行,因此在excel中執行操作的機會為null。
我剩下要做的事情類似:
Sequence=3433;Status=true;Report=223313;Profile=xxxx;
Sequence=0323;Status=true;Header=The;Report=43838;Profile=xxxx;
Sequence=5323;Status=true;Report=6541998;Profile=xxxx;
我希望這些設置為:
Sequence,Status;Report;Header;Profile
3433,true,Report=223313,,xxxx
0323,true,Report=43838,The,xxxx
5323,true,Report=6541998,,xxxx
這意味着我需要使用所有在其后帶有等號“ =”的部分來創建標題。 將處理文件中的所有其他操作,這將用於在文件之間進行比較檢查以及替換或附加字段。 因為我是python的新手,所以我只需要在我正在編寫的程序的這一部分提供幫助。
謝謝大家!
你可以試試看
首先,我調用了csv庫以減少放置逗號和引號的工作。
import csv
然后,我做了一個函數,該函數從您的日志文件中提取一行,並輸出帶有在標題中傳遞的字段的字典。 如果當前行的標題中沒有特定字段,它將保持為空字符串。
def convert_to_dict(line, header):
d = {}
for cell in header:
d[cell] = ''
row = line.strip().split(';')
for cell in row:
if cell:
key, value = cell.split('=')
d[key] = value
return d
由於文件的標題和字段數可能會有所不同,因此我做了一個提取它們的函數。 為此,我采用了一組獨特元素的集合,但它們也是無序的。 因此,我轉換為list
並使用了sorted
功能。 不要忘記seek(0)
調用來倒帶文件!
def extract_fields(logfile):
fields = set()
for line in logfile:
row = line.strip().split(';')
for cell in row:
if cell:
key, value = cell.split('=')
fields.add(key)
logfile.seek(0)
return sorted(list(fields))
最后,我編寫了主要代碼,在其中打開了要讀取的日志文件和要寫入的csv文件。 然后,它提取並寫入標題,並寫入每條轉換后的行。
if __name__ == '__main__':
with open('report.log', 'r') as logfile:
with open('report.csv', 'wb') as csvfile:
csvwriter = csv.writer(csvfile)
header = extract_fields(logfile)
csvwriter.writerow(header)
for line in logfile:
d = convert_to_dict(line, header)
csvwriter.writerow([d[cell] for cell in header])
這些是我用作示例的文件:
report.log
Sequence=3433;Status=true;Report=223313;Profile=xxxx;
Sequence=0323;Status=true;Header=The;Report=43838;Profile=xxxx;
Sequence=5323;Status=true;Report=6541998;Profile=xxxx;
report.csv
Header,Profile,Report,Sequence,Status
,xxxx,223313,3433,true
The,xxxx,43838,0323,true
,xxxx,6541998,5323,true
希望對您有所幫助! :D
編輯:我添加了對不同標題的支持。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.