Test directory permissions in Python? Test directory permissions in Python? windows windows

Test directory permissions in Python?


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)


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.


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.