0

我有一个 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)
4

2 回答 2

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)

或者,如果您想更改任何6行的第 2 列中的任何内容:

for i, row in enumerate(read):
    if row[2] == '6':
        row[2] = 'test'
    write.writenow(row)

… 等等。

于 2013-08-28T21:11:59.277 回答
0

if只需用一个块包装您的替换代码,然后使用enumerate()(请参阅#added 注释):

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)
于 2013-08-28T21:14:11.047 回答