Jyosua
Jyosua

Reputation: 649

os.path.exists Returns False w/ Escaped Paths Including Spaces

I've run across a seemingly strange issue in Python and all the Googling in the world hasn't helped. I'm trying to simply check whether or not a path exists in Python. The code below returns expected results with paths that do not have spaces, but as soon as there's a folder with a space, it no longer works.

import os

temp = "~/Documents/Example File Path/"
temp = temp.strip('\n')
tempexpanded = os.path.expanduser(temp)
tempesc = tempexpanded.replace(" ", "\\ ")
if not os.path.exists(tempesc):
    print "Path does not exist"
else:
    print "Path exists"

For some reason, this results in printing "Path does not exist", even though the following works if I type it into the terminal:

cd /Users/jmoore/Documents/Example\ File\ Path/

When I breakpoint my code, tempesc has a value of:

/Users/jmoore/Documents/Example\\ File\\ Path/

Given that, I'm not sure where I'm going wrong here? Any help is appreciated.

Upvotes: 4

Views: 5473

Answers (1)

John1024
John1024

Reputation: 113994

Don't escape the spaces:

In [6]: temp = "~/Documents/Example File Path/"

In [7]: tempexpanded = os.path.expanduser(temp)

In [8]: os.path.exists(tempexpanded)
Out[8]: True

The following shell command will fail:

cd ~/Documents/Example File Path/

The above has three strings: cd, ~/Documents/Example, File, and Path/. The cd command, however, wants only one argument.

The following will work even though the spaces are not escaped:

tempexpanded=~/'Documents/Example File Path/'
cd "$tempexpanded"

The above works because the spaces are part of one string. The same is true in your python code: the spaces are in one string variable.

Upvotes: 4

Related Questions