Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

To my shame, I can't figure out how to handle the exception of python 'with' statement. If I have a code:

with open("a.txt") as f:

print f.readlines()

I really want to handle 'file not found exception' in order to do something. But I can't write

with open("a.txt") as f:

print f.readlines()

except:

print 'oops'

and can't write

with open("a.txt") as f:

print f.readlines()

else:

print 'oops'

enclosing 'with' in a try/except statement doesn't work else: exception is not raised. What can I do in order to process failure inside 'with' statement in a Pythonic way?

1 Answer

0 votes
by (106k points)

If you want to catch an exception while using a Python 'with' statement use the following mentioned code and it will work:-

from __future__ import with_statement

try:

with open( "a.txt" ) as f :

print(f.readlines())

except EnvironmentError:

print('oops')

Related questions

0 votes
1 answer
asked Jul 2, 2019 in Python by ashely (50.2k points)
0 votes
1 answer
+2 votes
3 answers

Browse Categories

...