简体   繁体   English

try-except 与文件句柄(在哪里关闭)

[英]try-except with files handle (where to close)

Suppose I want to introduce a try-except block while handling a txt file.假设我想在处理 txt 文件时引入一个 try-except 块。 Which of the two following way of capturing the possible exception is correct?以下两种捕获可能异常的方法中哪一种是正确的?

try:
    h = open(filename)
except:
    h.close()
    print('Could not read file')



try:
    h = open(filename)
except:
  
    print('Could not read file')

In other words, should the h.close() be called even if the exception occurs or not?换句话说,即使发生异常,是否应该调用 h.close() ?

Secondly, suppose that you have the following code其次,假设您有以下代码

try:
    h = open(filename)
    "code line here1"
    "code line here2"
except:
    h.close()
    print('Could not read file')

If an error occurs in "code line here1", should I use h.close() in the except block?如果“code line here1”中出现错误,我应该在 except 块中使用 h.close() 吗?

Is there a difference with the previous coding lines?与之前的编码行有区别吗?

You should use with , it will close the file appropriately:您应该使用with ,它将适当地关闭文件:

with open(filename) as h:
   #
   # do whatever you need...
   # 
# when you get here, the file will be closed automatically.

You can enclose that in a try/except block if needed.如果需要,您可以将其包含在 try/except 块中。 The file will always be properly closed.该文件将始终正确关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM