Python - 替换CSV文件中行的值

时间:2015-02-09 18:24:13

标签: python csv

我有这个数据集:

['XXXX-XXXX', '0']
['XXXX-XXXX', '0']
['XXXX-XXXX', '0']
['XXXX-XXXX', '0']
['XXXX-XXXX', '0']
['XXXX-XXXX', '0']
['XXXX-XXXX', '0']
['XXXX-XXXX', '0']

基本上我想逐步改变第二个字段' 0'到' 1'每次运行程序后,如下所示:

['XXXX-XXXX', '1'] # first run
['XXXX-XXXX', '0']
['XXXX-XXXX', '0']
['XXXX-XXXX', '0']
['XXXX-XXXX', '0']
['XXXX-XXXX', '0']
['XXXX-XXXX', '0']
['XXXX-XXXX', '0']

['XXXX-XXXX', '1'] # second run
['XXXX-XXXX', '1']
['XXXX-XXXX', '0']
['XXXX-XXXX', '0']
['XXXX-XXXX', '0']
['XXXX-XXXX', '0']
['XXXX-XXXX', '0']
['XXXX-XXXX', '0']

['XXXX-XXXX', '1'] # eigth run
['XXXX-XXXX', '1']
['XXXX-XXXX', '1']
['XXXX-XXXX', '1']
['XXXX-XXXX', '1']
['XXXX-XXXX', '1']
['XXXX-XXXX', '1']
['XXXX-XXXX', '1']

应直接编辑.csv文件。关于如何解决这个问题我没有丝毫想法,我是一个蟒蛇新手..

1 个答案:

答案 0 :(得分:1)

这是让你朝着正确方向前进的东西。

with open('path/to/filename') as filehandler_name:
    # this is how you open a file for reading

with open('path/to/filename', 'w') as filehandler_name:
    # this is how you open a file for (over)writing
    # note the 'w' argument to the open built-in

import csv
# this is the module that handles csv files

reader = csv.reader(filehandler_name)
# this is how you create a csv.reader object
writer = csv.writer(filehandler_name)
# this is how you create a csv.writer object

for line in reader:
    # this is how you read a csv.reader object line by line
    # each line is effectively a list of the fields in that line
    # of the file.
    # # XXXX-XXXX, 0 --> ['XXXX-XXXX', '0']

对于小文件,您可以执行以下操作:

import csv

with open('path/to/filename') as inf:
    reader = csv.reader(inf.readlines())

with open('path/to/filename', 'w') as outf:
    writer = csv.writer(outf)
    for line in reader:
        if line[1] == '0':
            writer.writerow([line[0], '1')
            break
        else:
            writer.writerow(line)
    writer.writerows(reader)

对于inf.readlines会导致内存分配失效的大型文件,因为它会立即将整个文件拉入内存,您应该执行以下操作:

import csv, os

with open('path/to/filename') as inf, open('path/to/filename_temp', 'w') as outf:
    reader = csv.reader(inf)
    writer = csv.writer(outf)
    for line in reader:
        if line[1] == '0':
           ...
        ... # as above

os.remove('path/to/filename')
os.rename('path/to/filename_temp', 'path/to/filename')