Python-替换CSV文件中的一行的值 [英] Python - Replacing value of a row in a CSV file
本文介绍了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",
Basically I want to incrementally change the second field '0' to '1' after each run of the program, like this:
['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新手..
The .csv file should be edited directly. I haven't the slightest idea on how to approach this problem, I'm a python novice..
推荐答案
以下内容可以帮助您朝正确的方向前进.
Here's something to get you going in the right direction.
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']
对于小文件,您可以执行以下操作:
For small files, you could do something like:
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
会杀死您的内存分配的大型文件,因为它将立即将整个文件拉入内存,您应该执行以下操作:
For large files that inf.readlines
will kill your memory allocation since it's pulling the whole file into memory at once, and you should do something like:
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文件中的一行的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文