The Python Oracle

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

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Dreaming in Puzzles

--

Chapters
00:00 Question
00:39 Accepted answer (Score 3)
00:59 Answer 2 (Score 2)
01:15 Answer 3 (Score 2)
01:44 Thank you

--

Full question
https://stackoverflow.com/questions/4666...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #unix

#avk47



ACCEPTED ANSWER

Score 3


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).




ANSWER 2

Score 2


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.




ANSWER 3

Score 2


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)