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)
你可以使用这个:
>>> 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)
| 归档时间: |
|
| 查看次数: |
6714 次 |
| 最近记录: |