如何在Windows系统上使用pathlib输出正斜杠路径?

8
如何使用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并没有unlinkglob和其他pathlib中有用的工具,因此我无法完全使用它。在Windows系统上,PosixPath会抛出NotImplementedError。

这种情况在实际应用中很常见: zipfile.ZipFile要求路径中的斜杠必须是正斜杠(/),否则匹配失败。

有没有一种方法可以从pathlib请求正斜杠路径而不失去任何pathlib的功能呢?


你为什么在意呢?唯一可能导致 bug 的地方是如果你为一个批处理文件生成命令行。cmd shell 坚持使用反斜杠。每个 Win32 API 都可以接受任何一个。 - Tim Roberts
当然,你可以继承Path类并提供自己的__str__函数。 - Tim Roberts
以防万一,这里还有另一种丑陋的方法:"/".join(native.parts)。也许会稍微好看一点,或者不会出错。这取决于情况。 - Yuri Khristich
1个回答

17

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接