4

我在 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 的值为:

/用户/jmoore/文档/示例\\文件\\路径/

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

4

1 回答 1

4

不要逃避空格:

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 代码中也是如此:空格在一个字符串变量中。

于 2015-08-13T00:53:01.900 回答