Example of python reading multiple files at the same time

  • 2021-07-18 08:34:22
  • OfStack

The with statement is used to open text in Python, such as opening 1 file and reading every 1 line


with open(filename) as fp:
  for line in fp:
    # do something

To read multiple files at the same time, you can use the following code


with open(filename1) as fp1, open(filename2) as fp2, open(filename3) as fp3:
  for l1 in fp1:
    l2 = fp2.readline()
    l3 = fp3.readline()
    # do something

A little brief introduction can be made to use nested in contextlib, which has


from contextlib import nested
with nested(open(filename1), open(filename2), open(filename3)) as (fp1, fp2, fp3):
  for l1 in fp1:
    l2 = fp2.readline()
    l3 = fp3.readline()
    # do something

Related articles: