Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

Converting a log file into a csv file using Python

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

I need a complete csv file like so:

A1,B1,C1
A2,B2,C2
A3,B3,C3
...
An,Bn,Cn

How can I do this using a python script?

EDIT: Actually, the format is written out in the following way -

Voltage: A1
Current: B1
Power: C1

How can I convert it to -

Voltage, Current, Power
A1,B1,C1
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...