简体   繁体   English

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

[英]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结果我需要在 excel 作为

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)输出(out.csv 的内容)

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

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

相关问题 使用python解析具有重复值键对的文本文件 - Parsing Text file having repeated value key pair using python 如何将 python 字典的每个键值对存储在 json 文件中的单独行上? - How can I store each key-value pair of my python dictionary on a separate line in json file? 使用python从.txt文件中的键值对中提取值 - Extracting value from a key value pair in a .txt file using python 如何使用pandas读取文本文件的键值对? - How to read text file's key, value pair using pandas? 在python中读取一个YAML文件并通过匹配键值对来访问数据 - Reading a YAML file in python and accessing the data by matching key value pair 如何使用python将具有键值对的已抓取json数据保存为json文件格式 - How to save scraped json data with key value pair into a json file format using python Python:has_key,我想用if语句打印key的值 - Python: has_key , I want to print the value of the key with if statement 我需要使用 selenium python 在 map 之类的键值对中包含表数据 - I need to have table data in a map like key value pair using selenium python 使用python在文件中合并具有相同键值对的json对象 - Merge the json objects with same key value pair in a file using python 如果列表中没有键和值对,则使用python跳过此数据 - if there is not key and value pair in list then skip this data using python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM