hel*_*hod 1 python exception-handling with-statement
有了这个with声明,是否需要打开文件/检查异常/手动关闭资源,比如
try:
f = open('myfile.txt')
for line in f:
print line
except IOError:
print 'Could not open/read file'
finally:
f.close()
Run Code Online (Sandbox Code Playgroud)
您当前的代码尝试处理未找到的文件的异常,或者访问权限不足等等,这是with open(file) as f:块无法完成的.
此外,在这种情况下,finally:块将提升a,NameError因为f不会被定义.
在一个with块中,仍然会引发块中发生的任何异常(无论何种类型,可能在代码中除以零),但即使您不处理它,您的文件也将始终正确关闭.这是完全不同的东西.
你想要的可能是:
try:
with open("myfile.txt") as f:
do_Stuff() # even if this raises an exception, f will be closed.
except IOError:
print "Couldn't open/read myfile.txt"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
402 次 |
| 最近记录: |