Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...