在Python中处理多个文件时,如何避免使用嵌套的“with”语句

时间:2014-11-04 09:32:39

标签: python file design-patterns refactoring

当使用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()

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

1 个答案:

答案 0 :(得分:11)

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"))