Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 228
BoltzmannBrain Avatar asked Mar 19 '15 00:03

BoltzmannBrain


People also ask

How do you raise error type in Python?

TypeError is raised whenever an operation is performed on an incorrect/unsupported object type. For example, using the + (addition) operator on a string and an integer value will raise TypeError.

How do you raise a runtime error in Python?

As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.


1 Answers

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.

like image 115
MattDMo Avatar answered Oct 11 '22 21:10

MattDMo