Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In Python on Windows, is there a way to determine if a user has permission to access a directory? I've taken a look at os.access but it gives false results.

>>> os.access('C:haveaccess', os.R_OK)
False
>>> os.access(r'C:haveaccess', os.R_OK)
True
>>> os.access('C:donthaveaccess', os.R_OK)
False
>>> os.access(r'C:donthaveaccess', os.R_OK)
True

Am I doing something wrong? Is there a better way to check if a user has permission to access a directory?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
802 views
Welcome To Ask or Share your Answers For Others

1 Answer

It can be complicated to check for permissions in Windows (beware of issues in Vista with UAC, for example! -- see this related question).

Are you talking about simple read access, i.e. reading the directory's contents? The surest way of testing permissions would be to try to access the directory (e.g. do an os.listdir) and catch the exception.

Also, in order for paths to be interpreted correctly you have to use raw strings or escape the backslashes ('\'), -- or use forward slashes instead.

(EDIT: you can avoid slashes altogether by using os.path.join -- the recommended way to build paths)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...