ExitStack的push()和callback()方法的正确用例是什么?

时间:2019-09-13 05:09:40

标签: python-3.x

我已阅读有关ExitStack的Python文档,但无法理解如何将push()callback()应用于实际示例。

我尝试了Exitstack的基本示例来打开多个上下文管理器,并了解了enter_context()pop_all()close()方法的实际工作。

from contextlib import ExitStack
path = './folder/'
fileList = ['File1', 'File2', 'File3']

with ExitStack() as stack:
    files = [stack.enter_context(open(path+file)) for file in fileList]

    close_files = stack.pop_all().close

    for f in files:
        print(f.read())

    close_files()



path = './folder/'
fileList = ['File1', 'File2', 'File3']

with ExitStack() as stack:
    files = [stack.enter_context(open(path+file)) for file in fileList]

    close_files = stack.pop_all().close

    mergedFile = open(path+'mergedFile', 'w+')
    stack.callback(mergedFile.close)

    for f in files:
        print(mergedFile.writelines(f.readlines()))

    close_files()


0 个答案:

没有答案