views:

100

answers:

2
def CreateDirectory(pathName):
    if not os.access(pathName, os.F_OK):
        os.makedirs(pathName)

versus:

def CreateDirectory(pathName):
    if not os.path.exists(pathName):
        os.makedirs(pathName)

I understand that os.access is a bit more flexible since you can check for RWE attributes as well as path existence, but is there some subtle difference I'm missing here between these two implementations?

+11  A: 

Better to just catch the exception rather than try to prevent it. There are a zillion reasons that makedirs can fail

def CreateDirectory(pathName):
    try:
        os.makedirs(pathName)
    except OSError, e:
        # could be that the directory already exists
        # could be permission error
        # could be file system is full
        # look at e.errno to determine what went wrong

To answer your question, os.access can test for permission to read or write the file (as the logged in user). os.path.exists simply tells you whether there is something there or not. I expect most people would use os.path.exists to test for the existence of a file as it is easier to remember.

gnibbler
+2  A: 

os.access tests if the path can be accessed by the current user os.path.exists checks if the path does exist. os.access could return false even if the path exists.

Nikolaus Gradwohl