Check directory permissions in Python?

In Python on Windows, is there a way to determine if a user has permission to access a directory? I took 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?

+8
python windows directory permissions
Feb 11 '09 at 22:26
source share
3 answers

It can be difficult to check permissions on Windows (for example, beware of problems in Vista with UAC! - see this question) .

Are you talking about easy access to reading, that is, reading the contents of a directory? The surest way to check permissions is to try to access the directory (for example, make os.listdir ) and catch the exception.

In addition, to interpret the paths correctly, you need to use raw strings or avoid backslashes ('\\'), or use slashes instead.

(EDIT: you can avoid the slash at all by using os.path.join - the recommended way to create paths)

+7
Feb 11 '09 at 22:32
source share

While os.access tries to determine if the path is accessible or not, it does not claim to be perfect. From Python docs:

Note. I / O operations may not work even when access () indicates that they will succeed, especially for operations on network file systems that may have permission semantics outside the normal resolution bit of the POSIX model.

The recommended way to find out if the user has access to what needs to be done and to catch any exceptions that arise.

+5
Feb 11 '09 at 23:04
source share

Actually, 'C: \ hasaccess' is different from r'C: \ hasaccess'. From a Python perspective, 'C: \ hasaccess' is not a valid path, so use C: \\ hasaccess instead. I think os.access is working fine.

0
Mar 15 '10 at 8:23
source share



All Articles