简体   繁体   English

复制并修改csv文件中的一行

[英]Copy and modify a row in csv file

I need some help with a csv file.我需要一些有关 csv 文件的帮助。 I'm working with the CIS Automotive API and am extracting data to put in a database.我正在使用 CIS 汽车 API,并且正在提取数据以放入数据库。 I turned the data into a csv file, however there are some rows with multiple ID's.我将数据转换为 csv 文件,但是有些行具有多个 ID。 Is there anyway I can copy the row but with one ID each?无论如何我可以复制该行但每个都有一个ID吗?

The csv file is like this at the moment: csv文件现在是这样的:

Dealership     | Address       |Zipcode| DealerID
Charleston Kia | 123 Bowman rd | 29412 | 12345,21456,32145

and I wanted to make it to look like this:我想让它看起来像这样:

Dealership     | Address       |Zipcode| DealerID
Charleston Kia | 123 Bowman rd | 29412 | 12345
Charleston Kia | 123 Bowman rd | 29412 | 21456
Charleston Kia | 123 Bowman rd | 29412 | 32145

You can use aDictreader to read each row with the headers.您可以使用Dictreader读取带有标题的每一行。 Then,split() the DealerID column on commas, and replicate the row with the matching ID.然后,用逗号split() DealerID列,并复制具有匹配 ID 的行。

So for an input file file.csv like:所以对于输入文件file.csv像:

Dealership|Address|Zipcode|DealerID
Charleston Kia|123 Bowman rd|29412|12345,21456,32145

The following code:以下代码:

import csv

with open("file.csv") as file, open("new.csv", 'w', newline='') as out_file:
    reader = csv.DictReader(file, delimiter='|')
    writer = csv.DictWriter(out_file, fieldnames=reader.fieldnames)
    writer.writeheader()
    for row in reader:
        for _id in row["DealerID"].split(','):
            writer.writerow({**row, "DealerID": _id})

Will create a new file, new.csv with contents:将创建一个包含内容的新文件new.csv

Dealership,Address,Zipcode,DealerID
Charleston Kia,123 Bowman rd,29412,12345
Charleston Kia,123 Bowman rd,29412,21456
Charleston Kia,123 Bowman rd,29412,32145

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

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