python - os.path.exists 返回 False w/Escaped Paths Including Spaces

标签 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(" ", "\\ ")
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/ExampleFilePath/ .然而,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/

相关文章:

macos - 如何在 Mac(或在线)上查看 Azure 服务总线主题订阅的配置规则?

ios - 在 iOS 上将 UIView 导出为 png

python - 无论顺序如何,查找 2 个列表之间的公共(public)元素 - python 2

python - 有没有办法从导入的模块中获取 'parent' 模块的名称?

java - 使用 pem 证书打开 SSL 套接字

python - 检查多个文件是否相同

python - 使用 argparse,如何将用户输入放入列表中?

python - SWIG 从 c 中调用 python 代码

javascript - “listener” 参数必须是函数类型。 MacOS 上的 Node.JS 9.3.0_1 有问题

python - 如何使用 os.walk 根据修改日期过滤文件夹?