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

PythonServer Side ProgrammingProgramming

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
raja
Published on 06-Dec-2017 16:03:38
Advertisements