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

时间:2015-08-13 00:47:48

标签: python macos os.path

我在Python中遇到了一个看似奇怪的问题,世界上所有的Google搜索都没有帮助。我试图简单地检查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 /

鉴于此,我不确定我在哪里出错?任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:3)

不要逃离这些空间:

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/ExampleFilePath/。但是,cd命令只需要一个参数。

即使空格未转义,以下内容仍然有效:

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

以上是有效的,因为空格是一个字符串的一部分。你的python代码也是如此:空格是一个字符串变量。

相关问题