如何使用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
Run Code Online (Sandbox Code Playgroud)
PurePosixPathpathlib 中没有unlink、glob、 和其他有用的实用程序,因此我不能专门使用它。PosixPath在 Windows 上抛出 NotImplementedError。
这是必要的实际用例:zipfile.ZipFile需要正斜杠,但在给定反斜杠时无法匹配路径。
有没有某种方法可以从 pathlib 请求正斜杠路径而不丢失任何 pathlib 功能?