有了 with
语句,是否需要打开文件/检查异常/手动关闭资源,如
try:
f = open('myfile.txt')
for line in f:
print line
except IOError:
print 'Could not open/read file'
finally:
f.close()
最佳答案
您当前的代码会尝试处理未找到文件或访问权限不足等异常,而 with open(file) as f:
block 不会这样做。
此外,在这种情况下,finally:
block 会引发 NameError
,因为 f
不会被定义。
在 with
block 中, block 内 发生的任何异常(任何类型,可能是代码中被零除)仍将被引发,但即使如果您不处理它,您的文件将始终正常关闭。那是完全不同的东西。
你想要的可能是:
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"
关于Python with 语句——是否还需要旧式文件处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3996358/