Hi Stackoverflow,
What would be the best way in Python to determine whether a directory is writeable for the user executing the script? Since this will likely involve using the os module I should mention I'm running it under a *nix environment.
Hi Stackoverflow,
What would be the best way in Python to determine whether a directory is writeable for the user executing the script? Since this will likely involve using the os module I should mention I'm running it under a *nix environment.
It may seem strange to suggest this, but a common Python idiom is
It's easier to ask for forgiveness then for permission
Following that idiom, one could say:
Try writing to the directory in question, and catch the error if you don't have the permission to do so.
Check the mode bits:
def isWritable(name):
uid = os.geteuid()
gid = os.getegid()
s = os.stat(dirname)
mode = s[stat.ST_MODE]
return (
((s[stat.ST_UID] == uid) and (mode & stat.S_IWUSR)) or
((s[stat.ST_GID] == gid) and (mode & stat.S_IWGRP)) or
(mode & stat.S_IWOTH)
)
Although what Christophe suggested is a more Pythonic solution, the os module does have a function to check access:
os.access('/path/to/folder', os.W_OK)
# W_OK is for writing, R_OK for reading, etc.
If you only care about the file perms, os.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.
More generally, to avoid TOCTOU attacks (only a problem if your script runs with elevated privileges -- suid or cgi or so), you shouldn't really trust these ahead-of-time tests, but drop privs, do the open()
, and expect the IOError
.