python的with语句一般用于清理或者处理异常。
下面介绍下with在文件操作异常的处理语句。
python的with语句一般用于清理或者处理异常。
下面介绍下with在文件操作异常的处理语句。
# 不用with语句,这样做可能出现忘记关闭文件句柄,或者读取时出现异常
file = open("tmp.txt")
data = file.read()
file.close()
# try catch版本,该版本可以处理异常,但是代码太长
file = open("tmp.txt")
try:
data = file.read()
finally:
file.close()
# with版本,是不是优雅多了!
with open("tmp.txt") as file:
data = file.read()