我已阅读有关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()