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

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

问题描述

在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中检查权限可能很复杂(例如,请注意Vista中使用UAC的问题!-请参阅

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屋!

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