我有一个 CSV 文件,看起来像这样:
header1, header2, header3, header4
1, 2, 3, abc
4, 5, 6, abc
7, 8, 9, abc
我的目标是只更改标记为“abc”的值。我希望文件在完成后看起来像这样:
header1, header2, header3, header4
1, 2, 3, test
4, 5, 6, test
7, 8, 9, test
到目前为止,我提出的代码如下:
import csv
with open('test2-2.csv', 'w') as csvout:
write=csv.writer(csvout, delimiter=',', lineterminator='\r')
with open('test2.csv', 'rb') as csvfile:
read=csv.reader(csvfile, delimiter=',')
for row in read:
row[3]="test"
write.writenow(row)
这段代码的问题是它也覆盖了“header4”位置,所以它看起来像这样:
header1, header2, header3, test
1, 2, 3, test
4, 5, 6, test
7, 8, 9, test
有没有办法指定我要更改的索引位置?
谢谢你的帮助!
以下是适用于此示例的新代码:
import csv
with open('test2-2.csv', 'w') as csvout:
write=csv.writer(csvout, delimiter=',', lineterminator='\r')
with open('test.csv', 'rb') as csvfile:
read=csv.reader(csvfile, delimiter=',')
header=next(read)
write.writerow(header)
for row in read:
row[3]="test"
write.writerow(row)