windows中Python路径问题,,在Windows系统


在Windows系统中,路径使用的是\。而Linux系统中,路径使用的是/。\同时也是转义字符,所以使用\的时候会有问题。

如果运气好,\后没有可以转义的字符,还是可以正常输出:

print("C:\Program Files\Windows Media Player\wmplayer.exe")

下面是被转义的情况:

print("C:\Windows\notepad.exe")

想要正常获得文件路径就得加工一下字符串。

方法一:转义字符\表示\:

print("C:\Windows\notepad.exe")

这样加工字符串比较麻烦。

方法二:字符串前加r或R声明字符串不要转义:

print(r"C:\Windows\notepad.exe")

方法三:Python里也可以直接使用/表示Windows的路径。"C:\Windows\notepad.exe"可以直接写成"C:/Windows/notepad.exe"。

如果这里使用的是相对路径的话,用/表示路径的代码在两个平台下都可以正常运行。

windows中Python路径问题

评论关闭