Python 在 Windows 上使用 os.path.join 混合斜线
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16333569/
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
mixed slashes with os.path.join on windows
提问by nookie
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:
我倾向于只对路径('/')使用正斜杠,python 在 Windows 上也对它很满意。在 os.path.join 的描述中,它说如果你想跨平台,这是正确的方法。但是当我使用它时,我得到了混合斜线:
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/mySecondDirectory\myThirdDirectory\myExecutable.exe
Is this correct? Should I check and correct it afterward or there is a better way?
这样对吗?我应该事后检查并纠正它还是有更好的方法?
Thanks
谢谢
EDIT: I also get mixed slashes when asking for paths
编辑:我在询问路径时也会得到混合斜线
import sys
for item in sys.path:
print item
# Result:
C:\Program Files\Autodesk\Maya2013.5\bin
C:\Program Files\Autodesk\Maya2013.5\mentalray\scripts\AETemplates
C:\Program Files\Autodesk\Maya2013.5\Python
C:\Program Files\Autodesk\Maya2013.5\Python\lib\site-packages
C:\Program Files\Autodesk\Maya2013.5\bin\python26.zip\lib-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 Files\Nuke7.0v4\lib\site-packages
C:\Program Files\Nuke7.0v4/plugins/modules
采纳答案by pyrocumulus
You are now providing some of the slashes yourself and letting os.path.joinpick 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.
您现在自己提供一些斜线并让os.path.join选择其他斜线。最好让python选择所有这些或自己提供它们。Python 对路径的后半部分使用反斜杠,因为反斜杠是 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.
我还没有测试过这个,但我希望这会有所帮助。更常见的是有一个基本路径并且只需要加入一个其他元素,主要是文件。
By the way; you can use os.sepfor those moments you want to have the best separator for the operating system python is running on.
顺便一提; 您可以os.sep在那些想要为运行 python 的操作系统提供最佳分隔符的时刻使用。
Edit: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.
编辑:正如 dash-tom-bang 所述,显然对于 Windows,您确实需要为路径的根包含一个分隔符。否则,您将创建一个相对路径而不是绝对路径。
回答by ejrb
osadds slashes for you and makes sure not to duplicate slashes so omit them in your strings
os为您添加斜杠并确保不要重复斜杠,因此请在字符串中省略它们
import os
# Don't add your own slashes
a = 'C:'
b = 'myFirstDirectory'
c = 'mySecondDirectory'
d = 'myThirdDirectory'
e = 'myExecutable.exe'
print os.path.join(a, b, c, d, e)
C:\myFirstDirectory\mySecondDirectory\myThirdDirectory\myExecutable.exe
Additional:
额外的:
I'm unsure as to why you have mixed slashes in your sys path (have you used a linux os to add some folders?) but try checking
我不确定为什么你的 sys 路径中有混合斜杠(你是否使用了 linux os 添加了一些文件夹?)但尝试检查
print os.path.isdir(os.path.join('C:','Users','nookie')).
print os.path.isdir(os.path.join('C:','Users','nookie')).
If this is Truethen osworks for your mixed slashes.
如果这True则os适用于您的混合斜线。
Either way, I would avoid hard-coding directory names into your program. Your sys.pathfor loop is a safe way to pull out these directories. You can then use some string methods, or regex to pick the desired folder.
无论哪种方式,我都会避免将目录名称硬编码到您的程序中。您的sys.pathfor 循环是提取这些目录的安全方法。然后,您可以使用一些字符串方法或正则表达式来选择所需的文件夹。
回答by Maximus
You can use .replace()after path.join()to ensure the slashes are correct:
您可以使用.replace()afterpath.join()来确保斜线正确:
# .replace() all backslashes with forwardslashes
print os.path.join(a, b, c, d, e).replace("\","/")
This gives the output:
这给出了输出:
c:/myFirstDirectory/mySecondDirectory/myThirdDirectory/myExecutable.exe
As @sharpcloud suggested, it would be better to remove the slashes from your input strings, however this is an alternative.
正如@sharpcloud 所建议的那样,最好从输入字符串中删除斜杠,但这是一种替代方法。
回答by oriadam
EDIT based on comment:path = os.path.normpath(path)
根据评论编辑:path = os.path.normpath(path)
My previous answer lacks the capability of handling escape characters and thus should not be used:
我之前的答案缺乏处理转义字符的能力,因此不应使用:
- First, convert the path to an array of folders and file name.
Second, glue them back together using the correct symbol.
import os path = 'c:\www\app\my/folder/file.php' # split the path to parts by either slash symbol: path = re.compile(r"[\/]").split(path) # join the path using the correct slash symbol: path = os.path.join(*path)
- 首先,将路径转换为文件夹和文件名的数组。
其次,使用正确的符号将它们粘在一起。
import os path = 'c:\www\app\my/folder/file.php' # split the path to parts by either slash symbol: path = re.compile(r"[\/]").split(path) # join the path using the correct slash symbol: path = os.path.join(*path)
回答by Andre Odendaal
try using abspath (using python 3)
尝试使用 abspath(使用 python 3)
import os
a = 'c:/'
b = 'myFirstDirectory/'
c = 'mySecondDirectory'
d = 'myThirdDirectory'
e = 'myExecutable.exe'
print(os.path.abspath(os.path.join(a, b, c, d, e)))
OUTPUT:
输出:
c:\myFirstDirectory\mySecondDirectory\myThirdDirectory\myExecutable.exe
c:\myFirstDirectory\mySecondDirectory\myThirdDirectory\myExecutable.exe
Process finished with exit code 0
进程以退出代码 0 结束
回答by dinosaurwaltz
If for any reason you need to provide the paths yourself and you have using anything above python 3.4 you can use pathlib
如果出于任何原因您需要自己提供路径并且您使用了 python 3.4 以上的任何内容,则可以使用pathlib
from pathlib import Path, PurePosixPath
a = PurePosixPath('c:/')
b = PurePosixPath('myFirstDirectory/')
c = 'mySecondDirectory'
d = 'myThirdDirectory'
e = 'myExecutable.exe'
print(a / b / c / d / e)
# Result
c:/myFirstDirectory/mySecondDirectory/myThirdDirectory/myExecutable.exe
I used this when I needed a user to provide the location of an assets directory and my code was looking up using windows path strings
当我需要用户提供资产目录的位置并且我的代码正在使用 Windows 路径字符串查找时,我使用了它
In [1]: from pathlib import Path, PureWindowsPath
In [2]: USER_ASSETS_DIR = Path('/asset/dir') # user provides this form environment variable
In [3]: SPECIFIC_ASSET = PureWindowsPath('some\asset')
In [4]: USER_ASSETS_DIR / SPECIFIC_ASSET
Out[4]: PosixPath('/asset/dir/some/asset')
回答by ashrasmun
You can also do this:
你也可以这样做:
import re
a = 'c:/'
b = 'myFirstDirectory/'
c = 'mySecondDirectory'
d = 'myThirdDirectory'
e = 'myExecutable.exe'
joined = os.path.join(a, b, c, d, e)
formatted = re.sub(r'/|\', re.escape(os.sep), joined)
This is going to switch all your potentially mixed slashes into OS compliant ones.
这会将您所有可能混合的斜杠转换为符合操作系统的斜杠。
I know it's an ancient topic but I couldn't resist. :)
我知道这是一个古老的话题,但我无法抗拒。:)

