I am currently using Python 2 on a project that needs a Python 3 built-in exception: FileNotFoundError
. How do I do it?
The Python FileNotFoundError: [Errno 2] No such file or directory error is often raised by the os library. This error tells you that you are trying to access a file or folder that does not exist. To fix this error, check that you are referring to the right file or folder in your program.
The error "FileNotFoundError: [Errno 2] No such file or directory" is telling you that there is no file of that name in the working directory. So, try using the exact, or absolute path. In the above code, all of the information needed to locate the file is contained in the path string - absolute path.
You can of course define any exceptions you want.
But they're not going to do you any good. The whole point of FileNotFoundError
is that any Python operation that runs into a file-not-found error will raise that exception. Just defining your own exception won't make that true. All you're going to get is an OSError
(or IOError
, depending on 2.x version) with an appropriate errno
value. If you try to handle a custom FileNotFoundError
, your handler will never get called.
So, what you really want is (for example):
try:
f = open(path)
except OSError as e:
if e.errno == errno.ENOENT:
# do your FileNotFoundError code here
else:
raise
You could use IOError
instead:
Raised when an I/O operation (such as a print statement, the built-in open() function or a method of a file object) fails for an I/O-related reason, e.g., “file not found” or “disk full”.
This class is derived from EnvironmentError. See the discussion above for more information on exception instance attributes.
Changed in version 2.6: Changed socket.error to use this as a base class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With