9

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() ?

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
alaricljs
  • 370
  • 1
  • 2
  • 9

2 Answers2

15

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
Rehan Shikkalgar
  • 1,029
  • 8
  • 16
  • 6
    Unfortunately, this will catch any exception, not just File Not Found, and will disguise any program bugs that you may be unaware of. You can instead catch `FileNotFoundError` or `IOError`, depending on your version of Python. – LarsH May 22 '18 at 19:41
-3

If you're getting a FileNotFound error, the problem is most likely that the file name or the path to the file is incorrect. If you're trying to read AND write to a file that doesn't exist yet, change the mode from 'r' to 'w+'. It may also help to write out the full path before the file, for Unix users as:

'/Users/paths/file'

Or better yet, us os.path so that your path can be run on other operating systems.

import os
with open(os.path.join('/', 'Users', 'paths', 'file'), 'w+)
Breton
  • 15
  • 1
  • 5