Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 568
user407896 Avatar asked Aug 02 '10 13:08

user407896


2 Answers

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.

like image 108
John La Rooy Avatar answered Nov 02 '22 01:11

John La Rooy


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.

like image 43
Nikolaus Gradwohl Avatar answered Nov 02 '22 00:11

Nikolaus Gradwohl