Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused about the proper order of try and with in Python

I read here that it is recommended to use with open(filename) instead of using the pair open(filename) and filename.close() (at least for basic tasks) and that it is also better to use try.

Q1: If my understanding is correct, what would be the proper order ?

try:
  with open(filename) as f:
    do something, eg. match string

or

with open(filename) as f:
  try:
    do something, eg. match string

Q2: Which case is better if I want also to insert some code to bring up a popup for file handling error ? (for file not found, or something)

like image 883
secarica Avatar asked Apr 23 '14 09:04

secarica


1 Answers

Keep your try / except statement as close to the source of the exception as possible.

If you are not catching IOErrors, put it inside the with statement. On the other hand, if it is an exception that open() throws, put it around the with statement.

If the with statement is longer or you don't want to mask the same exception being raised in the with statement suite, execute the open() call first:

try:
    fileobj = open(filename)
except IOError:
    print('File problems!')
else:
    with fileobj as f:
        # do something
like image 106
Martijn Pieters Avatar answered Sep 24 '22 14:09

Martijn Pieters