在 python 中有没有比这个更好的方法来处理跨平台斜杠?

Is there better way to deal with cross platform slash than this in python?

如题。下面是我在处理跨平台路径时使用的代码。有比这更好的方法吗?

import platform

my_os = platform.system()
if my_os == "Windows":
    slash = "\"
else:
    slash = "/"

代码中的随机示例:

source_path = ""
for part in __file__.split("/")[:-1]:
    source_path += (part + slash)

print(source_path)

函数os.path.join。有关详细信息,请参阅文档:https://docs.python.org/3/library/os.path.html#os.path.join

不要自己加入路径。标准库都带有 os.path and pathlib 模块,它们抽象掉了(大部分)平台差异。

例如获取当前模块目录为:

import os.path

source_path = os.path.dirname(os.path.abspath(__file__))

import pathlib

source_path = pathlib.Path(__file__).resolve().parent

两者都为您提供适合当前平台的绝对路径。

还有 os.sep value, which is the main directory separator character for the current platform, as well as os.altsep 平台,例如 Windows 可以使用多个路径分隔符。

可以依靠标准库版本来处理特定于平台的边缘情况,例如 Windows 上的混合正斜杠和反斜杠、驱动器名称和 UNC 路径。