Python os.path.exists返回False w/包含空格的转义路径

Python os.path.exists返回False w/包含空格的转义路径,python,macos,os.path,Python,Macos,Os.path,我在Python中遇到了一个看似奇怪的问题,而世界上所有的谷歌搜索都没有帮助。我试图简单地检查Python中是否存在路径。下面的代码返回的路径没有空格的预期结果,但一旦有带空格的文件夹,它就不再工作 import os temp = "~/Documents/Example File Path/" temp = temp.strip('\n') tempexpanded = os.path.expanduser(temp) tempesc = tempexpanded.replace(" ",

我在Python中遇到了一个看似奇怪的问题,而世界上所有的谷歌搜索都没有帮助。我试图简单地检查Python中是否存在路径。下面的代码返回的路径没有空格的预期结果,但一旦有带空格的文件夹,它就不再工作

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"
出于某种原因,这会导致打印“路径不存在”,即使在终端中键入以下内容也有效:

cd /Users/jmoore/Documents/Example\ File\ Path/
当我中断代码时,tempesc的值为:

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


考虑到这一点,我不确定我会错在哪里?感谢您的帮助。

请勿逃离以下空间:

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

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

In [8]: os.path.exists(tempexpanded)
Out[8]: True
以下shell命令将失败:

cd ~/Documents/Example File Path/
上面有三个字符串:
cd
~/Documents/Example
文件
路径
。然而,
cd
命令只需要一个参数

即使未转义空间,以下操作仍有效:

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

上述方法之所以有效,是因为空格是一个字符串的一部分。python代码中也是如此:空格在一个字符串变量中。

您确定需要转义空格吗?试着不要逃避它们。只是想指出os.path.exists()的操作不同于os.system()。前者需要未转义的字符串,但通过os.system()执行的命令需要转义。感谢您的解释!既然你已经明确指出了原因,这似乎是显而易见的。哈哈,我希望我能早点意识到这一点。