Python CSV模块同时读写 [英] Python CSV Module read and write simultaneously
问题描述
我有两个.csv文件我在一个(文件a)中查找数据,并匹配到另一个(文件b)一旦我找到合适的行b我想写入相应行中的特定单元格。另外,我需要迭代这个,所以我可能会写入文件b中的每一行潜在几次。
我可以写一个csv文件,然后再读一遍吗?
def match(name,group,cnum):
masterfile_list中的数据:
if(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 =102):
data [17] = cnum
elif(cnum ==101):
data [18] = cnum
解决方案
div>
如果文件b不是非常大,我建议使用
readlines()
获得所有行的列表,然后遍历列表并根据需要更改行。这将比寻找文件中不同位置和替换行更容易一些。
此外,你可以显着减少函数体中的代码,我可能会做这样的事情:
def match(name,group,cnum):
lookup = dict (map(str,range(112,100,-1)),range(7,19)))
masterfile_list中的数据:
如果data [0] ]和cnum在查找:
data [lookup [cnum]] = cnum
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
这篇关于Python CSV模块同时读写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文