我有一系列文件:
part_files = [open(name, "w+") for name in part_names]
...
[part.close() for part in part_files]
即使中间有异常,我也希望以有保证的方式关闭它们。
我知道有两种方法,即try catch finally
和contextlib.nested
但是我想知道哪种方式更受欢迎,并且可以同时适用于2.7和3.0。据我所知,{3.0}中不推荐使用contextlib.nested
答案 0 :(得分:4)
在Python3.3 +中,您可以使用contextlib.ExitStack
。
在Python2(或旧版本的Python3)中,您可以使用contextlib2.ExitStack,可以使用
pip install contextlib2
try:
import contextlib
contextlib.ExitStack
except AttributeError:
import contextlib2 as contextlib
partnames = ['foo', 'bar', 'baz']
with contextlib.ExitStack() as stack:
# 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
files = [stack.enter_context(open(name, "w+")) for name in partnames]
print(files)
答案 1 :(得分:0)
这个怎么样:
part_files = []
try:
for name in part_names:
part_files.append(open(name, "w+"))
... do stuff ...
finally:
for part in part_files:
part.close()
如果在打开文件时抛出异常,它仍会关闭到目前为止已打开的所有文件