Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I import FileNotFoundError from Python 3?

I am currently using Python 2 on a project that needs a Python 3 built-in exception: FileNotFoundError. How do I do it?

like image 362
PSNR Avatar asked Nov 04 '14 21:11

PSNR


People also ask

How do I fix Python FileNotFoundError?

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.

Why I am getting file Not Found error?

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.


2 Answers

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
like image 108
abarnert Avatar answered Oct 22 '22 22:10

abarnert


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.

like image 7
Martin Thoma Avatar answered Oct 22 '22 23:10

Martin Thoma