繁体   English   中英

我的文本文件在键值对中有数据,我想使用 python 将其移动到 excel

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

文本中的数据就像

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

结果我需要在 excel 作为

id Name rollno
1 Jitu   44
2 Varun 5

一种方法:

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})

输出(out.csv 的内容)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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