如何使用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
并没有unlink
、glob
和其他pathlib中有用的工具,因此我无法完全使用它。在Windows系统上,PosixPath
会抛出NotImplementedError。
这种情况在实际应用中很常见: zipfile.ZipFile
要求路径中的斜杠必须是正斜杠(/),否则匹配失败。
有没有一种方法可以从pathlib请求正斜杠路径而不失去任何pathlib的功能呢?
Path
类并提供自己的__str__
函数。 - Tim Roberts"/".join(native.parts)
。也许会稍微好看一点,或者不会出错。这取决于情况。 - Yuri Khristich