Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to read two files at the same time in python? (with the same loop?)

Tags:

python

I am trying to read 2 files at the same time right now, but I get a "too many values to unpack error". Here is what I have:

for each_f, each_g in f, g :
    line_f = each_f.split()
    line_g = each_g.split()

I am a little new to python but I assumed I would be able to do this. If this is impossible, is there an equivalent method? (The two files I am reading are very large)

like image 788
Alex Brashear Avatar asked Jun 05 '13 14:06

Alex Brashear


People also ask

Can you read two files at the same time Python?

Python provides the ability to open as well as work with multiple files at the same time. Different files can be opened in different modes, to simulate simultaneous writing or reading from these files.


2 Answers

import itertools

# ...

for each_f, each_g in itertools.izip(f, g):
    # ...
like image 83
kirelagin Avatar answered Oct 18 '22 14:10

kirelagin


You can use a context manager, i.e. the with statement to read two files at the same time:

with open('file1', 'r') as a, open('file2', 'r') as b:  
    do_something_with_a_and_b
like image 35
pypat Avatar answered Oct 18 '22 13:10

pypat