如何避免嵌套的"with"?在Python中处理多个文件时的语句 [英] How to avoid nested "with" statements when working with multiple files in Python
问题描述
在Python代码中使用多个文件时,使用推荐的样式可能会很丑陋:
When working with multiple files in Python code can get ugly when using the recommended style:
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
这是三个缩进级别,仅用于处理文件!替代方法是这样
That's three indentation levels just for working with files! The alternative would be this
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()
我觉得可以将这两个示例中的任何一个都重构为更优雅的形式.有例子吗?
I have a feeling that either of these examples could be refactored to something more elegant. Any examples?
推荐答案
Python 2.7及更高版本允许您在一个 with
语句中指定多个上下文管理器:
Python 2.7 and up let you specify multiple context managers in one with
statement:
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个字符以下.您可以使用 \
反斜杠继续:
The line does get long, and you cannot use parentheses to keep that below 80 characters. You can use \
backslash continuations however:
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()
上下文管理器(仅在Python 3.3及更高版本中):
Another option would be to use contextlib.ExitStack()
context manager (only in Python 3.3 and up):
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"))
这篇关于如何避免嵌套的"with"?在Python中处理多个文件时的语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!