如何将路径字符串的格式更改为不同的操作系统?

jon*_*opf 3 python operating-system path

我需要将文件路径从 MAC 更改为 Windows,我正准备做一个简单.replace()的任何操作/\但我突然想到可能有更好的方法。所以例如我需要改变:

foo/bar/file.txt
Run Code Online (Sandbox Code Playgroud)

到:

foo\bar\file.txt
Run Code Online (Sandbox Code Playgroud)

小智 10

pathlib模块(在 Python 3.4 中引入)对此提供支持:

from pathlib import PureWindowsPath, PurePosixPath

# Windows -> Posix
win = r'foo\bar\file.txt'
posix = str(PurePosixPath(PureWindowsPath(win)))
print(posix)  # foo/bar/file.txt

# Posix -> Windows
posix = 'foo/bar/file.txt'
win = str(PureWindowsPath(PurePosixPath(posix)))
print(win)  # foo\bar\file.txt
Run Code Online (Sandbox Code Playgroud)

  • 对于转换为 posix 路径,这也是一个选项:`posix = PureWindowsPath(win).as_posix()` (4认同)

Bur*_*lid 5

你可以使用这个:

>>> s = '/foo/bar/zoo/file.ext'
>>> import ntpath
>>> import os
>>> s.replace(os.sep,ntpath.sep)
'\\foo\\bar\\zoo\\file.ext'
Run Code Online (Sandbox Code Playgroud)