defprocess_files(filenames): with ExitStack() as stack: # 动态添加多个文件上下文 files = [stack.enter_context(open(fname, 'r')) for fname in filenames] # 也可以添加非上下文对象(需手动清理) temp_data = stack.enter_context(tempfile.NamedTemporaryFile()) # 处理所有文件 for f in files: print(f.read(100)) # 读取每个文件前100字符 # 所有资源会在退出with块时自动释放
异步示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
from contextlib import AsyncExitStack import aiofiles
asyncdefprocess_async_files(urls): asyncwith AsyncExitStack() as stack: # 动态管理多个异步资源 files = [] for url in urls: # 异步打开文件(模拟) f = await stack.enter_async_context(aiofiles.open(url, 'r')) files.append(f) # 异步处理所有文件 contents = [] for f in files: contents.append(await f.read()) return contents