with as用法 --Python

有些任务,可能事先设置,时候做清理工作,如下面一段程序:

f = open('tmp.txt')
data = f.read()
print(data)

是不是忘了什么?没错,很明显忘记关闭文件句柄。另外,对文件读取可能发生的异常在程序中没有做任何处理。下面使用 try except finally来处理,

f = open('tmp.txt')
try:
    data = f.read()
    print(data)
except BaseException as msg:
    print(msg)
finally:
    f.close()

虽然这段代码运行良好,但太过冗长,这里使用 with as 来写是这样的,

with open('tmp.txt') as f:
    data = f.read()
    print(data)
原文地址:https://www.cnblogs.com/qikeyishu/p/11001532.html