【问题标题】:How to avoid nested "with" statements when working with multiple files in Python在 Python 中处理多个文件时如何避免嵌套的“with”语句
【发布时间】:2014-11-04 09:32:39
【问题描述】:

在 Python 代码中处理多个文件时,使用推荐的样式可能会变得很难看:

with open("foo.txt") as foo:
    with open("bar.txt", "w") as bar:
         with open("baz.txt", "w") as baz:
              # Read from foo, write different output to bar an baz

这只是用于处理文件的三个缩进级别!替代方案是这个

foo = open("foo.txt")
bar = open("bar.txt", "w")
baz = open("baz.txt", "w")
# Read from foo, write different output to bar an baz
foo.close()
bar.close()
baz.close()

我有一种感觉,这些示例中的任何一个都可以重构为更优雅的东西。有什么例子吗?

【问题讨论】:

  • with open('file1.txt') as f1, open('file2.txt') as f2: 这样做。

标签: python file design-patterns refactoring


【解决方案1】:

Python 2.7 及更高版本允许您在一个 with 语句中指定多个上下文管理器:

with open("foo.txt") as foo, open("bar.txt", "w") as bar, open("baz.txt", "w") as baz:
    # Read from foo, write different output to bar an baz

会变长,并且不能使用括号将其保持在 80 个字符以下。但是,您可以使用 \ 反斜杠继续:

with open("foo.txt") as foo,\
        open("bar.txt", "w") as bar,\
        open("baz.txt", "w") as baz:
    # Read from foo, write different output to bar an baz

另一种选择是使用contextlib.ExitStack() context manager(仅在 Python 3.3 及更高版本中):

from contextlib import ExitStack

with ExitStack() as stack:
    foo = stack.enter_context(open("foo.txt"))
    bar = stack.enter_context(open("bar.txt"))
    baz = stack.enter_context(open("baz.txt"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多