我有一个包含2行数据的csv文件,如下所示:
a1, b1, c1, d1
a2, b2, c2, d2
我想将第1行添加到数组中,然后将第2行添加到单独的数组中,如下所示:
row1 = ["a1", "b1", "c1", "d1"]
row2 = ["a2", "b2", "c2", "d2"]
我将数据写入csv文件的代码是这样的:
import csv
with open("file.csv", "w") as csvFile:
csvFileReader = csv.writer(csvFile, delimiter=";")
csvFileReader.writerows([[", ".join(arrValues1)],
[", ".join(arrValues2)]])
csvFile.close()
我该怎么做?
答案 0 :(得分:0)
要读取数据,请在next
对象上使用两次csv.reader
。 next
手动遍历编写器,除非读者精疲力尽,否则每次都会发布一行。
import csv
with open("file.csv", "r", newline="") as csvFile:
reader = csv.reader(csvFile, delimiter=",")
arrValues1 = next(reader)
arrValues2 = next(reader)
顺便说一句,首先要写入数组,您应该正确使用csv.writer
,而无需str.join
:
import csv
with open("file.csv", "w", newline="") as csvFile:
writer = csv.writer(csvFile, delimiter=",")
writer.writerows([arrValues1,arrValues2])