Ginko
Ginko

Reputation: 395

os.path.isdir() returns false on unaccessible, but existing directory

Lets say I have directories like:

foo/bar/

bar is chmod 777 and foo is 000.

When I call os.path.isdir('foo/bar') it returns just False, without any Permission Denied Exception or anything, why is it like that? Shouldn't it return True?

Upvotes: 7

Views: 1977

Answers (3)

pstatix
pstatix

Reputation: 3858

You could implement a try/except block:

import os

path = '/foo/bar'

if os.path.exists(path):
    try:
        os.chdir(path)
    except PermissionError:
        print ("Access Denied To:", path)

Upvotes: 2

mrCarnivore
mrCarnivore

Reputation: 5088

If you are not root then you cannot access foo. Therefore you can't check if foo/bar exists and it returns False because it cannot find a directory with that name (as it cannot access the parent directory).

Upvotes: 3

Jean-François Fabre
Jean-François Fabre

Reputation: 140307

os.path.isdir can return True or False, but cannot raise an exception.

So if the directory cannot be accessed (because parent directory doesn't have traversing rights), it returns False.

If you want an exception, try using os.chdir or os.listdir that are designed to raise exceptions.

Upvotes: 2

Related Questions