我有这个数据集:
['XXXX-XXXX', '0']
['XXXX-XXXX', '0']
['XXXX-XXXX', '0']
['XXXX-XXXX', '0']
['XXXX-XXXX', '0']
['XXXX-XXXX', '0']
['XXXX-XXXX', '0']
['XXXX-XXXX', '0']
Run Code Online (Sandbox Code Playgroud)
基本上,我想在每次程序运行后逐步将第二个字段“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']
Run Code Online (Sandbox Code Playgroud)
.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']
Run Code Online (Sandbox Code Playgroud)
对于小文件,您可以执行以下操作:
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)
Run Code Online (Sandbox Code Playgroud)
对于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')
Run Code Online (Sandbox Code Playgroud)