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