Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - with open() except (FileNotFoundError)? [duplicate]

It seems strange to me that

with open(file, 'r')

can report

FileNotFoundError: [Errno 2]

but I can't catch that in some way and continue on. Am I missing something here or is it really expected that you use isfile() or similar before a with open() ?

like image 889
alaricljs Avatar asked Nov 16 '16 19:11

alaricljs


Video Answer


1 Answers

use try/except to handle exception

 try:
     with open( "a.txt" ) as f :
         print(f.readlines())
 except Exception:
     print('not found')
     #continue if file not found
like image 141
Rehan Shikkalgar Avatar answered Nov 15 '22 16:11

Rehan Shikkalgar