Python - 测试目录权限 [英] Python - Test directory permissions
问题描述
在Windows中的Python中,有没有办法确定用户是否有访问目录的权限?我已经看过 os.access
,但它会产生错误的结果。
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?
推荐答案
检查权限可能很复杂在Windows中(请注意使用UAC的Vista中的问题,例如! - 请参阅相关问题)。
It can be complicated to check for permissions in Windows (beware of issues in Vista with UAC, for example! -- see this related question).
你在谈论简单的读取访问,即阅读目录的内容?
测试权限的最可靠方法是尝试访问目录(例如,执行 os.listdir
)并捕获异常。
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.
(编辑:通过使用 os.path.join
可以避免斜杠 - 建议的构建方法路径)
( you can avoid slashes altogether by using os.path.join
-- the recommended way to build paths)
这篇关于Python - 测试目录权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!