在 Windows 上使用 os.path.join 混合斜线 [英] mixed slashes with os.path.join on windows

查看:24
本文介绍了在 Windows 上使用 os.path.join 混合斜线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我倾向于只对路径('/')使用正斜杠,python 也很高兴在 Windows 上使用它.在 os.path.join 的描述中,它说如果你想跨平台,这是正确的方法.但是当我使用它时,我得到了混合斜线:

I tend to use only forward slashes for paths ('/') and python is happy with it also on windows. In the description of os.path.join it says that is the correct way if you want to go cross-platform. But when I use it I get mixed slashes:

import os

a = 'c:/'
b = 'myFirstDirectory/'
c = 'mySecondDirectory'
d = 'myThirdDirectory'
e = 'myExecutable.exe'


print os.path.join(a, b, c, d, e)

# Result:
c:/myFirstDirectory/mySecondDirectorymyThirdDirectorymyExecutable.exe

这是正确的吗?我应该事后检查并纠正它还是有更好的方法?

Is this correct? Should I check and correct it afterward or there is a better way?

谢谢

询问路径时我也得到混合斜线

I also get mixed slashes when asking for paths

import sys
for item in sys.path:
    print item

# Result:
C:Program FilesAutodeskMaya2013.5in
C:Program FilesAutodeskMaya2013.5mentalrayscriptsAETemplates
C:Program FilesAutodeskMaya2013.5Python
C:Program FilesAutodeskMaya2013.5Pythonlibsite-packages
C:Program FilesAutodeskMaya2013.5inpython26.ziplib-tk
C:/Users/nookie/Documents/maya/2013.5-x64/prefs/scripts
C:/Users/nookie/Documents/maya/2013.5-x64/scripts
C:/Users/nookie/Documents/maya/scripts
C:Program FilesNuke7.0v4libsite-packages
C:Program FilesNuke7.0v4/plugins/modules

推荐答案

您现在自己提供一些斜线并让 os.path.join 选择其他人.最好让python选择所有这些或自己提供它们.Python 在路径的后半部分使用反斜杠,因为反斜杠是 Windows 上的默认值.

You are now providing some of the slashes yourself and letting os.path.join pick others. It's better to let python pick all of them or provide them all yourself. Python uses backslashes for the latter part of the path, because backslashes are the default on Windows.

import os

a = 'c:' # removed slash
b = 'myFirstDirectory' # removed slash
c = 'mySecondDirectory'
d = 'myThirdDirectory'
e = 'myExecutable.exe'

print os.path.join(a + os.sep, b, c, d, e)

我还没有测试过这个,但我希望这会有所帮助.更常见的是有一个基本路径并且只需要加入一个其他元素,主要是文件.

I haven't tested this, but I hope this helps. It's more common to have a base path and only having to join one other element, mostly files.

顺便说一下;你可以在那些时刻使用 os.sep想要为运行 python 的操作系统提供最好的分隔符.

By the way; you can use os.sep for those moments you want to have the best separator for the operating system python is running on.

正如 dash-tom-bang 所述,显然对于 Windows,您确实需要为路径的根包含一个分隔符.否则,您将创建一个相对路径而不是绝对路径.

as dash-tom-bang states, apparently for Windows you do need to include a separator for the root of the path. Otherwise you create a relative path instead of an absolute one.

这篇关于在 Windows 上使用 os.path.join 混合斜线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆