简体   繁体   中英

My text file has data in key value pair and i want to move it to excel using python

Data in text is like

id:1
Name: Jitu
rollno: 44
id:2
Name : varun
rollno: 5

result i need in excel as

id Name rollno
1 Jitu   44
2 Varun 5

One approach:

import csv

# change data.csv to your input file_path
with open("data.csv") as infile:
    # change out.csv to your output file_path
    with open("out.csv", "w") as outfile:
        fieldnames = ['id', 'name', "rollno"]
        writer = csv.DictWriter(outfile, fieldnames=fieldnames)
        writer.writeheader()

        # iterate in chunks of 3
        for ii, name, rollno in zip(*[iter(infile)] * 3):
            ii = ii.split(":")[1].strip()
            name = name.strip().split(":")[1].strip()
            rollno = rollno.split(":")[1].strip()
            writer.writerow({'id': ii, 'name': name, "rollno": rollno})

Output (content of out.csv)

id,name,rollno
1,Jitu,44
2,varun,5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM