try-except 带文件句柄(关闭的地方)

try-except with files handle (where to close)

假设我想在处理 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')

如果“code line here1”中出现错误,我应该在 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')