[英]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我正在尝试将 4 个元素附加到 csv 文件中的行尾
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"我试图研究如何做到这一点的大多数搜索结果如何产生结果,例如“如何附加到 python 中的 csv 文件”
Can someone direct me in the correct way to solve this problem有人可以指导我以正确的方式解决这个问题吗
I advise you to use pandas module and read_csv method.我建议您使用 pandas 模块和 read_csv 方法。
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.您可以将 csv 文件读取到列表列表中,并在写回之前进行必要的操作。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.