'Python raise NotADirectoryError

I'm trying to raise an error when a directory does not exist, before I open files in that directory. According to this response I should use the most specific Exception constructor for my issue, which I think is NotADirectoryError. But running the code below I get NameError: global name 'NotADirectoryError' is not defined. Thanks in advance for any help!

import os
if not os.path.isdir(baselineDir):
  raise NotADirectoryError("No results directory for baseline.")

And if there's a better way to do this please suggest it, thanks.



Solution 1:[1]

You're likely using Python 2, which does not define NotADirectoryError. However, this is defined in Python 3, for exactly the purpose you're trying to use it for.

If you need to use Python 2, you'll need to define the error yourself through a class. Read through the docs about user-defined exceptions to learn about subclassing the Exception class and customizing it for your own needs, if necessary. Here's a very simple example:

class NotADirectoryError(Exception):
    pass

This will take the string passed to it and print it out, just like you want.

Solution 2:[2]

The error message is pretty clear: NotADirectoryError hasn't been defined. If you are trying to make up your own exception, @MattDMo points you to how to go about it. If you want to use an existing exception, IOError seems most appropriate.

Solution 3:[3]

Import the exception if you are aware of which module it belongs to:

from my.exception.module import NotADirectoryError

If not, you must define this class:

class NotADirectoryError(Exception):
    pass

Solution 4:[4]

Exceptions, generally, are classes. You have to create a NotADirectoryError class that is a subclass of something, probably exceptions.OSError since that's what the os module will raise in that case.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MattDMo
Solution 2 Scott Hunter
Solution 3
Solution 4 Eric Renouf