0 votes
1 view
in Python by (47.8k 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 (107k 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.5k points)
0 votes
1 answer
+2 votes
3 answers
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...