python中给csv替换数据_Python-替换CSV文件中的一行的值

1586010002-jmsa.png

I have this dataset:

['XXXX-XXXX', '0']

['XXXX-XXXX', '0']

['XXXX-XXXX', '0']

['XXXX-XXXX', '0']

['XXXX-XXXX', '0']

['XXXX-XXXX', '0']

['XXXX-XXXX', '0']

['XXXX-XXXX', '0']

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

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)

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值