运维网's Archiver
论坛
›
Python
› Python利用上下文实现类似with open功能
wheat
发表于 2018-8-13 12:13:24
Python利用上下文实现类似with open功能
import contextlib
@contextlib.contextmanager
def myopen(file, mode):
f = open(file, mode, encoding="utf-8")
try:
yield f
finally:
f.close()
with myopen("01-thread.py", 'r') as f:
print(f.read())
页:
[1]
查看完整版本:
Python利用上下文实现类似with open功能