我有一个看起来像这样的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)
答案 0 :(得分:1)
如果您只是想要一种单独处理标题行的方法,那很简单:只需单独处理第一行。
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=',')
header = next(read)
write.writerow(header)
for row in read:
row[3]="test"
write.writenow(row)
(请注意,这仍然与您的原始代码存在相同的错误 - 至少有一个拼写错误,writenow
,缺少skipinitialspace=True
等等。)
如果你想通过一些不同的规则改变事物,只需写一个不同的转换。只要你能用英语描述它,你就应该能够很容易地将它转换成Python。
例如,如果您想将任意列中的任何6
更改为test
:
for row in read:
row = ('test' if col == '6' else col for col in row)
write.writenow(row)
或者,如果您想将第3行的第2列更改为test
:
for i, row in enumerate(read):
if i == 3:
row[2] = 'test'
write.writenow(row)
或者,如果您想更改任意行第2列中的任何6
:
for i, row in enumerate(read):
if row[2] == '6':
row[2] = 'test'
write.writenow(row)
......等等。
答案 1 :(得分:0)
只需使用if
块包含替换代码,然后使用enumerate()
(请参阅#added comments):
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 enumerate(read): #modified
if row[0] >= 1: #added
row[1][3]="test"
write.writenow(row)