I'm trying to read two csv files at the same time and use variables from each of the multiple columns. I've tried everything and searched all over SO, but no luck. Here's my poor code:
with open("test1.csv","r",encoding="utf-8") as f, open("test2.csv","r",encoding="utf-8") as g:
fieldnames = ['username', 'password']
fieldnames2 = ['title', 'afflink']
rdr1 = csv.DictReader(f, delimiter=',', fieldnames=fieldnames)
rdr2 = csv.DictReader(g, delimiter=',', fieldnames=fieldnames2)
for row in rdr1:
for row in rdr2:
print(username, title)
time.sleep(1)
CodePudding user response:
Your nested loops probably don't do what you want, though you have not actually told us anything about what you want. The inner loop will consume all the data in the second file and then proceed to read the second line of the first file, but then you can't loop over the second file again (unless you close and reopen and start over from the beginning). Probably you want to read one line from each at a time.
with open("test1.csv","r",encoding="utf-8") as f, open("test2.csv","r",encoding="utf-8") as g:
# Fixed broken indentation here
fieldnames = ['username', 'password']
fieldnames2 = ['title', 'afflink']
rdr1 = csv.DictReader(f, delimiter=',', fieldnames=fieldnames)
rdr2 = csv.DictReader(g, delimiter=',', fieldnames=fieldnames2)
for d1, d2 in zip(rdr1, rdr2):
print(d1['username'], d2['title'])
If your real-life loop is more complex than this, perhaps combine the dictionaries with something like d1.update(d2)
. The main beef here is the observation that the DictReader objects return dictionaries (you have to use dict['key']
, not key
to retrieve the value for key
) and that you can use zip
to loop over pairs of values.