【问题标题】:try-except with files handle (where to close)try-except 与文件句柄(在哪里关闭)
【发布时间】:2022-01-22 12:11:41
【问题描述】:

假设我想在处理一个 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 open(filename) as h: 打开文件。然后当程序流离开with 块时它会自动关闭。而且你永远不应该使用空的except。指定要捕获的异常。

标签: python try-catch


【解决方案1】:

你应该使用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') 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    • 1970-01-01
    • 2011-09-29
    相关资源
    最近更新 更多