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?
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
We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy. Accept Learn more