如何在 Windows 上使用 pathlib 输出带有正斜杠的路径?
How can I output paths with forward slashes with pathlib on Windows?
如何使用 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()
对带正斜杠的字符串进行必要的转换。
如何使用 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()
对带正斜杠的字符串进行必要的转换。