78

我倾向于只对路径('/')使用正斜杠,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

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

谢谢

编辑:询问路径时,我也会得到混合斜线

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
4

9 回答 9

57

您可以使用.replace()afterpath.join()确保斜线正确:

# .replace() all backslashes with forwardslashes
print os.path.join(a, b, c, d, e).replace("\\","/")

这给出了输出:

c:/myFirstDirectory/mySecondDirectory/myThirdDirectory/myExecutable.exe

正如@sharpcloud 建议的那样,最好从输入字符串中删除斜杠,但这是一种替代方法。

于 2013-09-13T00:53:28.280 回答
38

您现在自己提供一些斜线并让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)

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

顺便一提; 您可以os.sep在您希望为运行 python 的操作系统提供最佳分隔符的那些时刻使用。

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

于 2013-05-02T08:45:36.773 回答
14

尝试使用 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)))

输出:

c:\myFirstDirectory\mySecondDirectory\myThirdDirectory\myExecutable.exe

进程以退出代码 0 结束

于 2016-11-26T22:59:12.803 回答
8

根据评论编辑: path = os.path.normpath(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)
    
于 2016-03-24T17:27:55.427 回答
5

如果出于任何原因您需要自己提供路径并且您使用了 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

当我需要用户提供资产目录的位置并且我的代码正在使用 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')
于 2017-11-28T11:13:19.823 回答
2

os adds slashes for you and makes sure not to duplicate slashes so omit them in your strings

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

print os.path.isdir(os.path.join('C:','Users','nookie')).

If this is True then os works for your mixed slashes.

Either way, I would avoid hard-coding directory names into your program. Your sys.path for loop is a safe way to pull out these directories. You can then use some string methods, or regex to pick the desired folder.

于 2013-05-02T08:44:20.490 回答
1

Postgres 命令客户端psql即使在 Windows 上也不接受反斜杠:

>psql -U user -h 111.111.111.111 -d mydb
psql (12.2, server 12.5 . . .
. . .
mydb=> \i C:\my\path\myscript.sql
C:: Permission denied

所以在执行时需要修复它Python 3.8.6。不想诉诸天真的字符串替换并使用现有功能:

script_path = Path(script_dir).resolve()
input_sql = f'\\i {script_path.joinpath("myscript.sql").as_posix()}\n'

但在引擎盖下它有:

# ...\Programs\Python\Python38\Lib\pathlib.py
    def as_posix(self):
        """Return the string representation of the path with forward (/)
        slashes."""
        f = self._flavour
        return str(self).replace(f.sep, '/')
于 2020-12-04T22:58:03.537 回答
0

你也可以这样做:

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)

这会将您所有可能混合的斜杠转换为符合操作系统的斜杠。

我知道这是一个古老的话题,但我无法抗拒。:)

于 2020-02-21T16:39:35.057 回答
0

我这样做的方式相当简单:rstrip从斜杠开始的所有路径,无论数量和正确性如何,都使用正确的分隔符添加连接这些路径。

import os

def join_path_regardless_of_separators(*paths):
    return os.path.sep.join(path.rstrip(r"\/") for path in paths)
 
a = 'c:/'
b = 'myFirstDirectory/'
c = 'mySecondDirectory'
d = 'myThirdDirectory\\\\\\/'
e = 'myExecutable.exe'
join_path_regardless_of_separators(a, b, c, d, e)
>>> 'c:\\myFirstDirectory\\mySecondDirectory\\myThirdDirectory\\myExecutable.exe'

使用它的另一种方法,同样的结果:

join_path_regardless_of_separators(*"""c:////\\\\
                                       myFirstDirectory/
                                       mySecondDirectory\\\\
                                       myThirdDirectory/////
                                       myExecutable.exe
                                    """.split())
于 2021-01-01T22:51:57.960 回答