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)
Keep your try
/ except
statement as close to the source of the exception as possible.
If you are not catching IOError
s, 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With