This question already has answers here:
Alternative to contextlib.nested with variable number of context managers
(4个答案)
四年前关闭。
我有一系列文件:
    part_files = [open(name, "w+") for name in part_names]
    ...
    [part.close() for part in part_files]

我想以有保证的方式关闭它们,即使两者之间有例外。
我知道有两种方法,即try catch finallycontextlib.nested但是我想知道哪个是首选的,并且可以同时在2.7和3.0上工作。据我所知,contextlib.nested在3.0中被弃用

最佳答案

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

关于python - Python以安全的方式关闭文件数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29302786/

10-12 18:08