Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
828 views
in Technique[技术] by (71.8m points)

windows - Test directory permissions in Python?

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

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

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...