当使用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()
我觉得这些例子中的任何一个都可以重构为更优雅的东西。有什么例子吗?
答案 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"))