How to check if directory exist or not on passing as a parameter in python?

Question:

I am trying to pass the directory as a parameter and checking its existence –

    def validatePath(DirectoryName):
        pathtodata="/temp/project/data/"
        if os.path.exists('pathtodata'DirectoryName):
           return True
        return False
    
    parser = argparse.ArgumentParser()
    parser.add_argument("DirectoryName", nargs='?', help="Input folder Name", type=str)
    args = parser.parse_args()
    myDir = args.DirectoryName
    validatePath(myDir)

Error : Syntax Error in line os.path.exists(‘pathtodata’DirectoryName):

Asked By: VIPIN KUMAR

||

Answers:

In Python the way you combine paths is not 'pathtodata'DirectoryName but rather os.path.join(pathtodata, DirectoryName).

Answered By: John Zwinck

You should use os.path.join():

Your code should look like:

def validatePath(DirectoryName):
    pathtodata="/temp/project/data/"
    pathtodir = os.path.join(parthtodata, DirectoryName)
    if os.path.exists(pathtodir):
       return True
    return False

parser = argparse.ArgumentParser()
parser.add_argument("DirectoryName", nargs='?', help="Input folder Name", type=str)
args = parser.parse_args()
myDir = args.DirectoryName
validatePath(myDir):
Answered By: Alexandru Martalogu

The os.path.join joins the paths according to your os delimiter and the os.path.exists checks if the path exists.

os.path.exists(os.path.join(pathtodata, DirectoryName))

What caused the syntax error earlier was

'pathtodata'DirectoryName

which is invalid python syntax regardless to the context.

More details in os.path documentation – https://docs.python.org/2/library/os.path.html

Answered By: Tom Ron
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.