我尝试了下面的代码,试图将目录分隔符更改为正斜杠 / 但仍然卡在反斜杠 \ 中。文档说该函数使用目录分隔符 os.sep 连接路径,但这在我的情况下不起作用。
import os
os.sep = '/'
print(os.sep)
print(os.path.join('.', 'path'))
请您参考如下方法:
我认为this回答了为什么 Python 使用特定分隔符的问题。
也就是说,您可以使用 Pathlib模块来构建您的路径并指定您是想要 Posix 路径还是 Windows 路径。
例子:
from pathlib import PurePosixPath, PureWindowsPath
print(PurePosixPath('some', 'silly', 'long', 'path'))
>> some/silly/long/path
print(PureWindowsPath('some', 'silly', 'long', 'path'))
>> some\silly\long\path
确保您使用PosixPath 和WindowsPath 的纯 版本。如果您尝试在 Posix 系统上使用 WindowsPath,您将收到以下错误:
NotImplementedError: cannot instantiate 'WindowsPath' on your system
这也在 docs 中指定:
If you want to manipulate Windows paths on a Unix machine (or vice versa). You cannot instantiate a
WindowsPathwhen running on Unix, but you can instantiatePureWindowsPath.
