The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Track title: CC H Dvoks String Quartet No 12 Ame

--

Chapters
00:00 Os.Path.Isdir() Returns False On Unaccessible, But Existing Directory
00:34 Accepted Answer Score 3
00:56 Answer 2 Score 2
01:20 Answer 3 Score 2
01:35 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)