【问题标题】:Python: Context manager with multiple objects? [duplicate]Python:具有多个对象的上下文管理器? [复制]
【发布时间】:2021-10-03 09:22:30
【问题描述】:

是否可以在 Python 中对多个对象使用 with 上下文管理器语法?

例如:

with open("file1.txt") as file1, open("file2.txt") as file2:
    file1.write("this is file 1")
    file2.write("this is file 2")

对该站点的duckduckgo 和内部搜索表明答案可能是“否”。鉴于可能的答案是“否”,下一个最佳选择是什么? (当然,如果答案是“是”,请告诉我怎么做。)

也许一组 nexted 上下文管理器,如下所示,会是一个很好的解决方案?

with open("file1.txt") as file1:
    with open("file2.txt") as file2:
        file1.write("this is file 1")
        file2.write("this is file 2")

有什么理由不想这样做吗?顺序可能很重要吗?

【问题讨论】:

  • 答案是肯定的,可以在同一行打开多个文件
  • 您是否尝试过您的第一个代码示例?这做到这一点的方式
  • 在 Python 2.5 中添加 with 语句时,它们仅限于单个上下文表达式。 Python 3.1 中添加了对多个上下文表达式的支持。

标签: python with-statement contextmanager


【解决方案1】:

这个

with open("file1.txt") as file1, open("file2.txt") as file2:
    file1.write("this is file 1")
    file2.write("this is file 2")

符合docs给出的with语句定义

with_stmt ::=  "with" with_item ("," with_item)* ":" suite
with_item ::=  expression ["as" target]

* 表示 0 次或多次重复

【讨论】:

  • 很高兴知道我的猜测是正确的,但找不到这样的例子
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-22
  • 1970-01-01
  • 2011-03-02
  • 1970-01-01
  • 2015-01-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多