Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test directory permissions in Python?

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?

like image 997
Sean Avatar asked Feb 11 '09 22:02

Sean


People also ask

How do I check permissions on a directory?

Right-click on any file/folder, and select “Properties”. To check the permissions, head to the “Permission” tab.

How do I check file permissions in Python?

To check whether current process has permissions on a certain file, we could use os. access which is based on the access system call.

How do I check if a directory is writable in Python?

access(path, os. W_OK) should do what you ask for. If you instead want to know whether you can write to the directory, open() a test file for writing (it shouldn't exist beforehand), catch and examine any IOError , and clean up the test file afterwards.


2 Answers

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)

like image 200
dF. Avatar answered Sep 27 '22 18:09

dF.


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:

Note: I/O operations may fail even when access() indicates that they would succeed, particularly for operations on network filesystems which may have permissions semantics beyond the usual POSIX permission-bit model.

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.

like image 32
Theran Avatar answered Sep 27 '22 18:09

Theran