user407896 user407896 - 4 months ago 13
Python Question

Python - difference between os.access and os.path.exists?

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?

Answer

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.

Comments