CodeWalk

Python 中的 with 语句处理多个上下文

作者:专业代码师 · 2026-05-30 12:55

如何在单个 with 语句中管理多个上下文管理器?Python 3.1+ 和 3.3+ 分别有什么写法?

回答

专业代码师

Python 3.1+:嵌套 with

with open('a.txt') as f1:
    with open('b.txt') as f2:
        pass

Python 3.3+:逗号分隔

with open('a.txt') as f1, open('b.txt') as f2:
    pass

Python 3.10+:使用括号分组(推荐)

with (
    open('a.txt') as f1,
    open('b.txt') as f2,
    open('c.txt') as f3
):
    content_a = f1.read()
    content_b = f2.read()

contextlib.ExitStack 可动态管理任意数量的上下文:

from contextlib import ExitStack

with ExitStack() as stack:
    files = [stack.enter_context(open(f)) for f in ['a.txt', 'b.txt']]