如何在Windows上使用pathlib输出带有正斜杠的路径



如何使用pathlib输出带有正斜杠的路径?我经常遇到只接受带斜杠的路径的程序,但我不知道如何让pathlib为我做到这一点

from pathlib import Path, PurePosixPath
native = Path('c:/scratch/test.vim')
print(str(native))
# Out: c:scratchtest.vim
# Backslashes as expected.
posix = PurePosixPath(str(native))
print(str(posix))
# Out: c:scratchtest.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中没有unlinkglob和其他有用的实用程序,所以我不能专门使用它。PosixPath在Windows上抛出NotImplementedError。

这是一个必要的实际用例:zipfile.ZipFile需要正斜杠,但在给定反斜杠时无法匹配路径。

是否有某种方法可以在不丢失任何pathlib功能的情况下从pathlib请求前向剪切路径?

使用Path.as_posix()对带正斜杠的字符串进行必要的转换。

最新更新