使用Python将日志文件转换为CSV文件 [英] Converting a log file into a csv file using Python
本文介绍了使用Python将日志文件转换为CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在工作中遇到以下问题-我需要获取一个日志文件,其中的各项安排如下:
I have the following problem at work - I need to take a log file with items arranged as follows:
A1
B1
C1
A2
B2
C2
.
.
.
An
Bn
Cn
我需要一个完整的csv文件,如下所示:
I need a complete csv file like so:
A1,B1,C1
A2,B2,C2
A3,B3,C3
...
An,Bn,Cn
如何使用python脚本执行此操作?
How can I do this using a python script?
实际上,格式是通过以下方式写出的-
Actually, the format is written out in the following way -
Voltage: A1
Current: B1
Power: C1
如何将其转换为-
Voltage, Current, Power
A1,B1,C1
推荐答案
import csv
with open('myfile.log') as file:
lines = file.read().splitlines()
lines = [lines[x:x+3] for x in range(0, len(lines), 3)]
with open('yourcsv.csv', 'w+') as csvfile:
w = csv.writer(csvfile)
w.writerows(lines)
请注意,点仍然存在,它们将被视为值(因此它们也将由逗号分隔)
Note that the dots are still there and they would be treated as values (so they'll be separated by comma's too)
这篇关于使用Python将日志文件转换为CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文