我在 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
、File
、Path/
.然而,cd
命令只需要一个参数。
即使空格没有被转义,下面的代码仍然有效:
tempexpanded=~/'Documents/Example File Path/'
cd "$tempexpanded"
上面的工作是因为空格是一个字符串的一部分。在您的 Python 代码中也是如此:空格在一个字符串变量中。
关于python - os.path.exists 返回 False w/Escaped Paths Including Spaces,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31977768/