Home > python > Catch a specific IOError

Catch a specific IOError

If you want to open a non-existing file, you get the following error message: “IOError: [Errno 2] No such file or directory:...“. How to catch this specific IOError? For instance you want to notify the user that the file is missing instead of just saying “an I/O error occurred”.


def read_data_file(self):
        with open(self.data_file) as f:
           return json.load(f)
    except IOError, e:
        if e.errno == errno.ENOENT:
            print "Error: the given file doesn't exist."

Errno 2 == errno.ENOENT.

This tip is from here.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: