常用形式:
with open('output.txt', 'w') as f:
f.write('Hi there, !')
内在机制:
类似try...except...finally
, 在with
的block中try
,不管是否出现异常,都会 finally
关闭打开的文件,即使在循环中遭遇了continue
或者break
也照样以 finally
形式执行关闭
可以多重:
with A() as a, B() as b:
do something