[英]How can I output paths with forward slashes with pathlib on Windows?
How can I use pathlib to output paths with forward slashes?如何使用 pathlib 输出带正斜杠的路径? I often run into programs that accept paths only with forward slashes, but I can't figure out how to make pathlib do that for me.我经常遇到只接受带有正斜杠的路径的程序,但我不知道如何让 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
doesn't have unlink
, glob
, and other useful utilities in pathlib, so I can't work exclusively with it. PurePosixPath
在PurePosixPath
中没有unlink
、 glob
和其他有用的实用程序,所以我不能专门使用它。 PosixPath
throws NotImplementedError on Windows. PosixPath
在 Windows 上抛出 NotImplementedError。
A practical use case where this is necessary: zipfile.ZipFile
expects forward slashes and fails to match paths when given backslashes.一个必要的实际用例: zipfile.ZipFile
需要正斜杠,但在给定反斜杠时无法匹配路径。
Is there some way to request a forward-slashed path from pathlib without losing any pathlib functionality?有什么方法可以在不丢失任何 pathlib 功能的情况下从 pathlib 请求正斜杠路径吗?
使用Path.as_posix()
将必要的转换为带正斜杠的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.