我在 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/文档/示例\\文件\\路径/
鉴于此,我不确定我在哪里出错了?任何帮助表示赞赏。