Python Windows 路径斜线 [英] Python windows path slash
问题描述
我在 python 脚本中使用目录路径时遇到了一个非常基本的问题.当我从 Windows 资源管理器复制路径时,它使用反斜杠作为路径分隔符,这会导致问题.
<预><代码>>>>X'D:\测试文件夹'>>>打印 xD: est文件夹>>>打印 os.path.normpath(x)D: est文件夹>>>打印 os.path.abspath(x)D:\est文件夹>>>打印 x.replace('\\','/')D: est文件夹有人可以帮我解决这个问题吗.
Python 将字符串中的 \t
解释为制表符;因此,正如您所注意到的,"D:\testfolder"
将在 :
和 e
之间打印出一个制表符.如果您想要一个实际的反斜杠,您需要通过将其输入为 \\
来转义反斜杠:
但是,为了跨平台兼容性,您可能应该使用 os.path.join
.我认为 Windows 上的 Python 也会自动正确处理正斜杠 (/
).
I am facing a very basic problem using directory path in python script. When I do copy path from the windows explorer, it uses backward slash as path seperator which is causing problem.
>>> x
'D:\testfolder'
>>> print x
D: estfolder
>>> print os.path.normpath(x)
D: estfolder
>>> print os.path.abspath(x)
D:\ estfolder
>>> print x.replace('\\','/')
D: estfolder
Can some one please help me to fix this.
Python interprets a \t
in a string as a tab character; hence, "D:\testfolder"
will print out with a tab between the :
and the e
, as you noticed. If you want an actual backslash, you need to escape the backslash by entering it as \\
:
>>> x = "D:\\testfolder"
>>> print x
D:\testfolder
However, for cross-platform compatibility, you should probably use os.path.join
. I think that Python on Windows will automatically handle forward slashes (/
) properly, too.
这篇关于Python Windows 路径斜线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!