FileNotFoundError is a subclass of OSError, catch that or the exception itself:
except OSError as e:
Operating System exceptions have been reworked in Python 3.3; FileNotFoundError was added, and IOError has been merged into OSError. See the PEP 3151: Reworking the OS and IO exception hierarchy section in the What's New documentation.
For more details the OS Exceptions section for more information, scroll down for a class hierarchy.
That said, your code should still just work as IOError is now an alias for OSError:
>>> IOError
<class 'OSError'>
Make sure you are placing your exception handler in the correct location. Take a close look at the traceback for the exception to make sure you didn't miss where it is actually being raised. Last but not least, you did restart your Python script, right?
Answer from Martijn Pieters on Stack OverflowFileNotFoundError is a subclass of OSError, catch that or the exception itself:
except OSError as e:
Operating System exceptions have been reworked in Python 3.3; FileNotFoundError was added, and IOError has been merged into OSError. See the PEP 3151: Reworking the OS and IO exception hierarchy section in the What's New documentation.
For more details the OS Exceptions section for more information, scroll down for a class hierarchy.
That said, your code should still just work as IOError is now an alias for OSError:
>>> IOError
<class 'OSError'>
Make sure you are placing your exception handler in the correct location. Take a close look at the traceback for the exception to make sure you didn't miss where it is actually being raised. Last but not least, you did restart your Python script, right?
Change your OSError to (IOError, OSError) that should work.
@Thomas Wagenaar
Python's "open()" throws different errors for "file not found" - how to handle both exceptions? - Stack Overflow
Python - with open() except (FileNotFoundError)? - Stack Overflow
ERR: in python >= 3.5 use FileNotFoundError instead of OSError
How to differentiate different IOErrors?
In 3.3, IOError became an alias for OSError, and FileNotFoundError is a subclass of OSError. So you might try
except (OSError, IOError) as e:
...
This will cast a pretty wide net, and you can't assume that the exception is "file not found" without inspecting e.errno, but it may cover your use case.
PEP 3151 discusses the rationale for the change in detail.
This strikes me as better than a simple except:, but I'm not sure if it is the best solution:
error_to_catch = getattr(__builtins__,'FileNotFoundError', IOError)
try:
f = open('.....')
except error_to_catch:
print('!')
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
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+)
I'm learning about try-except blocks but I'm encountering this Name Error whenever I try to deal with a potential File Not Found Error. Here is my code:
try:
with open("mytext.txt", "r") as f_obj:
x = f_obj.read()
print (x)
except FileNotFoundError:
print "You don't have this file, bro"I run the script, and I get "NameError: name 'FileNotFoundError' is not defined"..Any ideas?
Pass in arguments:
import errno
import os
raise FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), filename)
FileNotFoundError is a subclass of OSError, which takes several arguments. The first is an error code from the errno module (file not found is always errno.ENOENT), the second the error message (use os.strerror() to obtain this), and pass in the filename as the 3rd.
The final string representation used in a traceback is built from those arguments:
>>> print(FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), 'foobar'))
[Errno 2] No such file or directory: 'foobar'
In Python, a variable can refer to the type (class), or an object (instance of the class):
>>> x = FileNotFoundError
>>> print(type(x))
<class 'type'>
>>> x = FileNotFoundError()
>>> print(type(x))
<class 'FileNotFoundError'>
While it's possible to also throw the type FileNotFoundError, you practically always want to throw an object that has been constructed from the class. The constructor accepts the same arguments as OSError. You can pass a standard POSIX and Windows error code, but it's enough to pass an error message. (In your case the standard error message "No such file or directory" is not entirely accurate, since you also throw the error if a directory is found.)
if not os.path.isfile("nothing.txt"):
raise FileNotFoundError("nothing.txt was not found or is a directory")