Python with

原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/12233607.html

with

with语句从Python 2.5开始引入,实现了上下文管理协议,实现了__enter__() 和 __exit__() 方法。

没有使用上下文管理器之前的代码:

file = open('test.txt', encoding='utf-8')

try:
    data = file.read()
    print(data)
finally:
    file1.close()

使用上下文管理器之后的代码:

with open('test.txt', encoding='utf-8') as file:
    data = file.read()
    print(data)

使用with语句之后,文件的打开、关闭以及异常的捕获都不用考虑了,高效方便。

Reference

https://www.runoob.com/python3/python3-file-methods.html

原文地址:https://www.cnblogs.com/agilestyle/p/12233607.html