假设我想在处理txt文件时引入一个try-except块。以下两种捕获可能异常的方法中哪一种是正确的?
try:
h = open(filename)
except:
h.close()
print('Could not read file')
try:
h = open(filename)
except:
print('Could not read file')
换句话说,即使异常发生与否,是否也应该调用h.close((?
其次,假设您有以下代码
try:
h = open(filename)
"code line here1"
"code line here2"
except:
h.close()
print('Could not read file')
如果在";这里的代码行1";,我应该在except块中使用h.close((吗?
与以前的编码行有什么不同吗?
您应该使用with
,它会适当地关闭文件:
with open(filename) as h:
#
# do whatever you need...
#
# when you get here, the file will be closed automatically.
如果需要,可以将其包含在try/except块中。文件将始终正确关闭:
try:
with open(filename) as h:
#
# do whatever you need...
#
except FileNotFoundError:
print('file not found')