Python Windows 路径斜线
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19065115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python windows path slash
提问by sarbjit
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.
我在 python 脚本中使用目录路径面临一个非常基本的问题。当我从 Windows 资源管理器复制路径时,它使用反斜杠作为导致问题的路径分隔符。
>>> 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.
有人可以帮我解决这个问题。
回答by mipadi
Python interprets a \tin 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 escapethe backslash by entering it as \\:
Python 将\t字符串中的 a解释为制表符;因此,如您所见,"D:\testfolder"将在:和之间打印出一个制表符e。如果你想要一个实际的反斜杠,你需要通过输入它来转义反斜杠\\:
>>> 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.
但是,为了跨平台兼容性,您可能应该使用os.path.join. 我认为 Windows 上的 Python 也会自动/正确处理正斜杠 ( )。

