Search code examples
pythonpython-module

os.path.exists not working properly on Python CLI


I've Python 2.5.x on my Windows 7 machine.

os.path.exists('C:')              # returns True
os.path.exists('C:\Users')        # returns True
os.path.exists('C:\Users\alpha')  # returns False, when ALPHA is a user on my machine

I've given read/write permissions to the CLI I'm using. What could be the possible reason for this ?


Solution

  • Inside quotes, '\' escapes the next character; see the reference on string literals. Either double your backslashes like:

    os.path.exists('C:\\Users\\ALPHA')
    

    to escape the backslashes themselves, use forward slashes as path separators as Michael suggests, or use "raw strings":

    os.path.exists(r'C:\Users\ALPHA')
    

    The leading r will cause Python not to treat the backslashes as escape characters. That's my favorite solution to dealing with Windows pathnames because they still look like people expect them to.