'Handle Error: Not a directory python

I get the following error:

[Errno 20] Not a directory:

What I have tried so far:

for i in range(3):
    numOfData = len(dir_2[i])
    try:
        for j in range(numOfData):
            print os.listdir(os.path.join(dir_1[i], dir_2[i][j]))
    except OSError:
        print "Hello"

Is there a better way to handle this?



Solution 1:[1]

You could of course check if the directory exists before running os.listdir() using os.path.isdir().

But that would not protect you against directory permissions, for instance (if it can be a problem). In that case, it would be tempting to use os.access() to see if you can read the directory except that it isn't that reliable

So trying to read and catching the specific OSError exception seems correct (better ask for forgiveness than permission), maybe with a os.path.isdir() first to print a nicer message for the user if the directory doesn't exist at all.

And seeing your comment, I realize that you should put the try/except block within the loop so if there's an error, you can still process the next directory.

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 Community