Python - 替换 CSV 文件中一行的值

Python - Replacing value of a row in a CSV file

我有这个数据集:

['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 文件。我对如何解决这个问题一无所知,我是一个 python 新手..

这里有一些东西可以让你朝着正确的方向前进。

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')