python csv模块 一次读多行,Python CSV模块同时读写

I have two .csv files I am looking up data in one (file a) and matching it to the other (file b) once I find the appropriate row in b I want to write to a specific cell in the appropriate row. Additionally I need to iterate over this so I will likely be writing to each row in file b potentially several times.

can I write to a csv file and then read it over and over again?

def match(name, group, cnum):

for data in masterfile_list:

if (name in data[0]):

if (group in data[4]):

if (cnum == "112"):

data[7] = cnum

elif (cnum == "111"):

data[8] = cnum

elif (cnum == "110"):

data[9] = cnum

elif (cnum == "109"):

data[10] = cnum

elif (cnum == "108"):

data[11] = cnum

elif (cnum == "107"):

data[12] = cnum

elif (cnum == "106"):

data[13] = cnum

elif (cnum == "105"):

data[14] = cnum

elif (cnum == "104"):

data[15] = cnum

elif (cnum == "103"):

data[16] = cnum

elif (cnum == "102"):

data[17] = cnum

elif (cnum == "101"):

data[18] = cnum

I would ideally write/replace the line that matches.

解决方案

If file b is not extremely large I would suggest using readlines() to get a list of all lines and then iterate over the list and change lines as needed. This will be quite a bit easier than seeking to different positions in the file and replacing lines.

Also, you can significantly reduce the code in the body of your function, I would probably do something like this:

def match(name, group, cnum):

lookup = dict(zip(map(str, range(112, 100, -1)), range(7, 19)))

for data in masterfile_list:

if name in data[0] and group in data[4] and cnum in lookup:

data[lookup[cnum]] = cnum

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值