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中。我应该如何完成此代码?
答案 0 :(得分:0)
我假设您想将“ somecities_update.csv”的记录追加到“ somecities.csv”的末尾。
为此,您可以在追加模式(mode='a'
)中打开“ somecities.csv”文件,从“ somecities_update.csv”中读取每一行并将其复制到somecities.csv”中。
以下代码演示了此插入:
import io
import csv
with io.open("somecities.csv", mode='a', encoding='utf-8') as dst:
writer = csv.writer(dst, lineterminator='\n')
with io.open(
"somecities_update.csv", mode='r', encoding='utf-8') as src:
reader = csv.reader(src)
headers = next(reader)
for record in reader:
writer.writerow(record)
警告:仅当“ somecities.csv”文件已经存在时,此脚本才有效。否则,将不会生成标题。
注意:您需要使用writer.writerow
。