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
216 views
in Technique[技术] by (71.8m points)

python 3.x - How to parse file with square brackets?

I have a data file like this :


[TOP]
Name=                 1
Plic=                 11
Glab=                 5487
Gendr=                2261
Mars=                 0
[ENDTOP]
[TOP]
Name=                 2
Plic=                 13
Glab=                 5556
Gendr=                2321
Mars=                 E
[ENDTOP]
[TOP]
Name=                 2
Plic=                 55
Glab=                 4012
Gendr=                3758
Mars=                 2
[ENDTOP]

I need to parse it with python3 to a csv file with header :

Name;Plic;Glab;Gendr;Mars
1;11;5487;2261;0
2;13;5556;2321;E
2;55;4012;3758;2

But I'm stuck with it; I tried with dict but it only keeps the last keys :

for line in f.readlines():
        line = ligne.split('=')
        if len(line) == 2:
            table[line[0].strip()]= line[1].strip()

Can someone help me to achieve it?

question from:https://stackoverflow.com/questions/66054334/how-to-parse-file-with-square-brackets

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

1 Reply

0 votes
by (71.8m points)

It's a pretty simple file format. This code parses the file into an list of dictionaries. It should be easy to save to a csv from there.

all_data = []
for line in f.readlines():
    if line.strip() == "[TOP]":
        # Start - create empty dictionary
        line_data = {}
    elif line.strip() == "[ENDTOP]":
        # End - save dictionary to list
        all_data.append(line_data)
    else:
        # Data - save to dictionary
        data = line.split('=')
        if len(data) == 2:
            line_data[data[0]] = data[1].strip()

Produces:

[
{'Name': '1', 'Plic': '11', 'Glab': '5487', 'Gendr': '2261', 'Mars': '0'},
{'Name': '2', 'Plic': '13', 'Glab': '5556', 'Gendr': '2321', 'Mars': 'E'},
{'Name': '2', 'Plic': '55', 'Glab': '4012', 'Gendr': '3758', 'Mars': '2'}
]

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

...