views:

548

answers:

4

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.

+12  A: 

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.

ChristopheD
+1 Python or not, this is really the most reliable way to test for access.
John Knoeller
This also takes care of other errors that can happen when writing to the disk - no diskspace left for example. That's the power of trying .. you dont need to remember everything that can go wrong ;-)
THC4k
Thanks guys. Decided to go with os.access as speed is an important factor in what I'm doing here although I can certainly understand the merits in "it's easier to ask for forgiveness than for permission." ;)
illuminatedtiger
@illuminatedtiger: that's perfectfly fine, just be aware of the notes in the documentation (http://docs.python.org/library/os.html#os.access)
ChristopheD
+1  A: 

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)
     )
Joe Koberg
+12  A: 

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.

Max Shawabkeh
Depending on the situation, the "easier to ask for forgiveness" is not the best way, even in Python. It is sometimes advisable to "ask permission" as with the os.access() method mentioned, for example when the probability of having to catch an error is high.
mjv
+1  A: 

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.

sverkerw