Determining Whether a Directory is Writeable Determining Whether a Directory is Writeable python python

Determining Whether a Directory is Writeable


Although what Christophe suggested is a more Pythonic solution, the os module does have the os.access function to check access:

os.access('/path/to/folder', os.W_OK) # W_OK is for writing, R_OK for reading, etc.


It may seem strange to suggest this, but a common Python idiom is

It's easier to ask for forgiveness than for permission

Following that idiom, one might say:

Try writing to the directory in question, and catch the error if you don't have the permission to do so.


My solution using the tempfile module:

import tempfileimport errnodef isWritable(path):    try:        testfile = tempfile.TemporaryFile(dir = path)        testfile.close()    except OSError as e:        if e.errno == errno.EACCES:  # 13            return False        e.filename = path        raise    return True

Update:After testing the code again on Windows I see that there is indeed an issue when using tempfile there, see issue22107: tempfile module misinterprets access denied error on Windows.In the case of a non-writable directory, the code hangs for several seconds and finally throws an IOError: [Errno 17] No usable temporary file name found. Maybe this is what user2171842 was observing?Unfortunately the issue is not resolved for now so to handle this, the error needs to be caught as well:

    except (OSError, IOError) as e:        if e.errno == errno.EACCES or e.errno == errno.EEXIST:  # 13, 17

The delay is of course still present in these cases then.