class fp(object): def __init__(self, fileobj, mode): self.fileobj = open(fileobj, mode) def __enter__(self): return self.fileobj def __exit__(self, type, value, Traceback): self.fileobj.close() return True with fp("abc1.txt", "w+") as fi: fi.write("测试上下文管理器")
from contextlib import contextmanager @contextmanager def fp(fileobj, mode): f = open(fileobj, mode) yield f f.close() with fp("abc2.txt", "w+") as fi: fi.write("context测试上下文管理器")
原文:https://www.cnblogs.com/yhleng/p/10674986.html