【发布时间】:2019-03-01 14:25:58
【问题描述】:
import csv
with open("somecities.csv", "r") as csvinput:
with open(" somecities_update.csv", "w") as csvresult:
writer = csv.writer(csvresult, lineterminator='\n')
reader = csv.reader(csvinput)
all = []
headers = next(reader)
for row in reader:
all.append(row)
# writing to the new file from here
writer.write(headers)
for record in all:
writer.write(record)
somecities.csv 内容:
Country,Capital,CountryPop,AreaSqKm
Canada,Ottawa,35151728,9984670
USA,Washington DC,323127513,9833520
Japan,Tokyo,126740000,377972
Luxembourg,Luxembourg City,576249,2586
somecities_update 我想添加的数据:
(Brazil, Brasília, 211224219, 8358140)
(China, Beijing, 1403500365, 9388211)
(Belgium, Brussels, 11250000, 30528)
在循环遍历包含数据的旧 CSV 文件的过程中,我已经做到了这一点,但现在我不知道去哪里包含新数据并将其打印在 somecities_update.csv 中。我应该如何完成这段代码?
【问题讨论】:
-
只需在循环中使用
writer.write(record)编写每个元组,其中record是您的元组列表中的一个元组(使用循环) -
您也可以将 csvs 作为 pandas 数据帧读取,并将两个数据帧连接起来:
df = pd.concat([df1,df2]),然后将该数据帧输出为 csv。