在 "with" 上下文中同时打开两个文件

Opening two files simultaneously on a "with" context

我想知道 Python 3 中是否有允许我在同一 with 上下文中打开两个(或更多)文件的结构。

我要找的是这样的:

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...

上面的代码显然是无效的,所以才会出现这个问题。

使用逗号:

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 涵盖了多个上下文表达式的情况。

正确的是with file1.open() as f1, file2.open() as f2:

取决于你想用f1f2做什么你可以直接使用 pathlib.Path.read_text() and pathlib.Path.write_text(),例如

from pathlib import Path

file1 = Path('file1.txt')
content = file1.read_text()
print(content)