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

I try to read 2 files at the same time, but I get "too many values ​​to unpack the 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'm a little new to python, but suggested I could do this. If this is not possible, is there an equivalent method? (The two files I read are very large)

+6
source share
3 answers
 import itertools # ... for each_f, each_g in itertools.izip(f, g): # ... 
+8
source

Without using itertools :

 while True: try: f_line = next(f) g_line = next(f) except StopIteration: break 

This breaks out of the loop as soon as the shorter of the two files is exhausted, like izip .

But really, itertools is an excellent solution.

+1
source

You can use the context manager, i.e. a 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 
-1
source

Source: https://habr.com/ru/post/946599/


All Articles