问题描述
如何使用 pathlib 输出带正斜杠的路径?我经常遇到只接受带有正斜杠的路径的程序,但我不知道如何让 pathlib 为我做到这一点。
from pathlib import Path,PurePosixPath
native = Path('c:/scratch/test.vim')
print(str(native))
# Out: c:\scratch\test.vim
# Backslashes as expected.
posix = PurePosixPath(str(native))
print(str(posix))
# Out: c:\scratch\test.vim
# Why backslashes again?
posix = PurePosixPath('c:/scratch/test.vim')
print(str(posix))
# Out: c:/scratch/test.vim
# Works,but only because I never used a Path object
posix = PurePosixPath(str(native))
print(str(posix).replace('\\','/'))
# Out: c:/scratch/test.vim
# Works,but ugly and may cause bugs
PurePosixPath
在 pathlib 中没有 unlink
、glob
和其他有用的实用程序,所以我不能专门使用它。 PosixPath
在 Windows 上抛出 NotImplementedError。
需要这样做的实际用例:zipfile.ZipFile
需要正斜杠,但在给定反斜杠时无法匹配路径。
有什么方法可以在不丢失任何 pathlib 功能的情况下从 pathlib 请求正斜杠路径吗?
解决方法
使用 Path.as_posix()
将必要的转换为带正斜杠的字符串。