6

I'm wondering if there is a construction in Python 3 that allows me to open two (or more) files on the same with context.

What I'm looking for is something like this:

from pathlib import Path

file1 = Path('file1.txt')
file2 = Path('file2.txt')

with file1.open() as f1 and file2.open() as f2:
    '''do something with file handles...

The code above is obviously invalid, which leads to this question.

sanyassh
  • 8,100
  • 13
  • 36
  • 70
accdias
  • 5,160
  • 3
  • 19
  • 31

2 Answers2

9

Use comma:

from pathlib import Path

file1 = Path('file1.txt')
file2 = Path('file2.txt')

with file1.open() as f1, file2.open() as f2:
    '''do something with file handles...

Documentation for with statement covers the case for multiple context expressions.

sanyassh
  • 8,100
  • 13
  • 36
  • 70
3

The correct one is with file1.open() as f1, file2.open() as f2:

Depending on what you want to do with f1 and f2 you can use directly pathlib.Path.read_text() and pathlib.Path.write_text(), e.g.

from pathlib import Path

file1 = Path('file1.txt')
content = file1.read_text()
print(content)
buran
  • 13,682
  • 10
  • 36
  • 61