简体   繁体   中英

Append Data to the end of a row in a csv file (Python)

I am attempting to append 4 elements to the end of a row in a csv file

Original
toetag1,tire11,tire12,tire13,tire14

Desired Outcome
toetag1,tire11,tire12,tire13,tire14,wtire1,wtire2,wtire3,wtire4

I attempted to research ways to do this how ever most search results yielded results such as "how to append to a csv file in python"

Can someone direct me in the correct way to solve this problem

I advise you to use pandas module and read_csv method.

You can use the following code for instance :

data = pandas.read_csv("your_file.csv")
row = data.iloc[0].to_numpy()
row.append(['wtire1','wtire2','wtire3','wtire4'])

You can read the csv file to a list of lists and do the necessary manipulation before writing it back.

import csv

#read csv file
with open("original.csv") as f:
    reader = csv.reader(f)
    data = [row for row in reader]

#modify data
data[0] = data[0] + ["wtire1", "wtire2", "wtire3", "wtire4"]

#write to new file
with open("output.csv", "w") as f:
    writer = csv.writer(f)
    writer.writerows(data)

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