1、with...as用法
with所求的对象必须有一个enter,一个exit方法
【普通】
file = open("/tmp/foo.txt") data = file.read() file.close()
可能会忘记close或者read不成功 没有进行任何处理。
【with】
with open("/tmp/foo.txt") as file: data = file.read()
等同于:
file = open("/tmp/foo.txt") try: data = file.read() finally: file.close()
无论是否成功,都会close,with在执行完代码自动调用exit方法