在Python中测试目录权限?
在Windows上的Python中,有没有办法确定用户是否有权访问目录? 我查看了 os.access,但它给出了错误的结果。
>>> 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
难道我做错了什么? 有没有更好的方法来检查用户是否有权访问目录?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 Windows 中检查权限可能很复杂(例如,请注意 Vista 中 UAC 的问题! - 请参阅此 相关问题)。
您是在谈论简单的读取访问,即读取目录的内容吗?
测试权限的最可靠方法是尝试访问目录(例如执行
os.listdir
)并捕获异常。另外,为了正确解释路径,您必须使用原始字符串或转义反斜杠('\\'),--或使用正斜杠。
(编辑:您可以使用 os.path.join 来完全避免斜杠——这是构建路径的推荐方法)
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)虽然 os.access 尽力判断路径是否可访问,但它并不声称是完美的。 来自Python文档:
确定用户是否有权执行任何操作的推荐方法是尝试执行该操作,并捕获发生的任何异常。
While os.access tries its best to tell if a path is accessible or not, it doesn't claim to be perfect. From the Python docs:
The recommended way to find out if the user has access to do whatever is to try to do it, and catch any exceptions that occur.
实际上 'C:\haveaccess' 与 r'C:\haveaccess' 不同。
从 Python 的角度来看,'C:\haveaccess' 不是有效路径,因此请使用 'C:\\haveaccess' 代替。
我认为 os.access 工作得很好。
Actually 'C:\haveaccess' is different than r'C:\haveaccess'.
From Python point of view 'C:\haveaccess' is not a valid path, so use 'C:\\haveaccess' instead.
I think os.access works just fine.
我将提供@dF.使用
os.scandir
/os.listdir
和 EAFP:I will provide code for @dF.'s approach of using
os.scandir
/os.listdir
with EAFP: