Search code examples
pythonpython-2.7joinpath

Python path.exists and path.join


Python 2.7: Struggling a little with path.exists

import os
import platform
OS = platform.system()
CPU_ARCH = platform.machine()

if os.path.exists( os.path.join("/dir/to/place/" , CPU_ARCH) ):
    print "WORKED"
    # Linux
    LD_LIBRARY_PATH = "/dir/to/place/" + CPU_ARCH
    TRANSCODER_DIR  = LD_LIBRARY_PATH + "/Resources/"
else:
    print "FAILED"
    #fail back to original director if processor not recognised
    TRANSCODER_DIR  = "/dir/to/place/Resources/"
    LD_LIBRARY_PATH = "/dir/to/place"

As soon as I stick os.path.join with a variable inside it the if statement fails.

os.path.exists("/dir/to/place/arch")

returns TRUE

os.path.exists("/dir/to/place/" + CPU_ARCH)

returns FALSE

I have tried many variations on the different path commands and to string commands none of them allow me to change this with a variable.

os.path.join("/dir/to/place/", CPU_ARCH)

returns /dir/to/place/arch

it's not a permissions issues either full perms granted and I've tested using the python cli on it's own still the same issue.

I've looked at all the stack posts for the same issue and the only response I've seen that someone says has worked is to strip the white space, I'm pretty new to python I don't see any whitespace on this.


Solution

  • os.path.exists checks if a path exists.

    if /dir/to/place/arch exists, then

    os.path.exists("/dir/to/place/" + CPU_ARCH)
    

    should return True. Notice the trailing / after place that is missing in your example

    os.path.join will join all its arguments to create a path.

    # This joins the two arguments into one path
    os.path.join("/dir/to/place/", CPU_ARCH)
    # >>> '/dir/to/place/x86_64'
    

    Explaining your results.