对于with嵌套如何优化
shihuizhen opened this issue · comments
shihuizhen commented
感谢作者的分享,优美的文笔,恰当的例子,让我觉得我以前写的不是python。
对于with嵌套作者有没有好的优化思路?写代码的时候遇到要打开多个文件,嵌套好几层with获取 文件对象,感觉很丑。
piglei commented
你好,普通的写法就是全部摊开来,比如:
with open('foo.txt') as f1, open('bar.txt') as f2:
...
也可以使用 contextlib.ExitStack 。文档里就有一个示例:
For example, a set of files may easily be handled in a single with statement as follows:
with ExitStack() as stack:
files = [stack.enter_context(open(fname)) for fname in filenames]
# All opened files will automatically be closed at the end of
# the with statement, even if attempts to open files later
# in the list raise an exception
Each instance maintains a stack of registered callbacks that are called in reverse order when the instance is closed (either explicitly or implicitly at the end of a with statement). Note that callbacks are not invoked implicitly when the context stack instance is garbage collected.
shihuizhen commented
谢谢作者。