Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to catch an exception while using a Python 'with' statement?

I have a code:

with open("myFile.txt") as foo:
    print foo.readlines()
else:
    print 'No such file or directory'

How to raise exception while using python ‘with’ statement?


1 Answer
Manogna

The code can be rewritten to catch the exception as follows:

try:
     with open("myFile.txt") as f:
          print(f.readlines())
except:
    print('No such file or directory')

We get the following output

C:/Users/TutorialsPoint1/~.py
No such file or directory
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.