在 Python 中测试目录权限? [英] Test directory permissions in Python?

查看:25
本文介绍了在 Python 中测试目录权限?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Windows 上的 Python 中,有没有办法确定用户是否有权访问目录?我查看了 os.access 但它给出了错误的结果.

<预><代码>>>>os.access('C:haveaccess', os.R_OK)错误的>>>os.access(r'C:haveaccess', os.R_OK)真的>>>os.access('C:donthaveaccess', os.R_OK)错误的>>>os.access(r'C:donthaveaccess', os.R_OK)真的

我做错了吗?有没有更好的方法来检查用户是否有权访问目录?

解决方案

在 Windows 中检查权限可能很复杂(例如,当心带有 UAC 的 Vista 中的问题! - 请参阅此 相关问题).

您是在谈论简单的读取访问,即读取目录的内容吗?测试权限最可靠的方法是尝试访问目录(例如执行 os.listdir)并捕获异常.

此外,为了正确解释路径,您必须使用原始字符串或转义反斜杠 ('\'),或使用正斜杠代替.

(您可以通过使用 os.path.join 来完全避免斜线——推荐的构建路径的方法)

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?

解决方案

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)

这篇关于在 Python 中测试目录权限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆