Test directory permissions in Python?
Asked Answered
O

4

8

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?

Ontogeny answered 11/2, 2009 at 22:26 Comment(1)
The first and third accesses are failing because the \h is getting interpreted as an (invalid) escape sequenceRodl
H
7

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)

Heartache answered 11/2, 2009 at 22:32 Comment(1)
Good answer, but on your last point, using os.path.join or os.path.sep is better than creating paths manually.Musicale
G
5

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.

Goa answered 11/2, 2009 at 23:4 Comment(0)
G
0

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.

Gaskins answered 15/3, 2010 at 8:23 Comment(1)
'C:\haveaccess' is a valid path because \h doesn't mean anything special, so it works (out of pure luck but it works)Fleece
C
0

I will provide code for @dF.'s approach of using os.scandir/os.listdir with EAFP:

def can_access(path: str) -> bool:
    """Check if we can access folder on network drive"""
    try:
        os.scandir(path)
        return True
    except PermissionError:
        return False
Cantabrigian answered 17/7, 2023 at 11:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.