PwNzDust
PwNzDust

Reputation: 281

try-except with files handle (where to close)

Suppose I want to introduce a try-except block while handling a txt file. 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?

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?

Is there a difference with the previous coding lines?

Upvotes: 1

Views: 640

Answers (1)

Alain T.
Alain T.

Reputation: 42143

You should use with, it will close the file appropriately:

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. The file will always be properly closed:

try:
    with open(filename) as h:
        #
        # do whatever you need...
        #
except FileNotFoundError:
    print('file not found') 

Upvotes: 1

Related Questions