gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:50:09 25 4
gpt4 key购买 nike

我有这个数据集:

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

关于Python - 替换CSV文件中一行的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28416678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com