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?


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):

    f = open(path)
except OSError as e:
    if e.errno == errno.ENOENT:
        # do your FileNotFoundError code here

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.

You can simply create the FileNotFoundError exception yourself:

class FileNotFoundError(OSError):

This new exception class inherits from OSError just like the one in Python 3.x.

Here is a reference on User-defined Exceptions in Python.

Need Your Help

get result from ssh2_exec


I have a script that makes a SSH connection to a server (this works fine). Now I want to execute a command and echo the result I get from this command.

Voice Recognition Software For Developers

speech-recognition voice ergonomics speech code-by-voice

Well the docs finally said it, I need to take it easy on my wrist for a few months. Being that I'm a .NET Developer this could end my livelihood for a little while, something I'm not anxious to do....