且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么 os.path.join 不使用 os.path.sep 或 os.sep?

更新时间:2023-01-09 21:31:16

为什么不定义自定义显示功能?

Why not define a custom display function?

例如

def display_path(path):
    return path.replace("\", "/")

如果你想用 str.join 代替 os.path.join,你可以这样做(str.join 期望单个列表,os.path.join 需要 *args):

And if you want to substitute str.join for os.path.join, you can just do this (str.join expects a single list, os.path.join expects *args):

join = lambda *args: "/".join(args)

也许更好的是让 Python 规范化所有内容,然后替换,例如:

Perhaps better would be to let Python normalize everything, then replace, e.g.:

join = lambda *args: os.path.join(*args).replace("\", "/")

当文件路径中有空格时,上述唯一的问题可能是在 posix 上.

The only issue with the above might be on posix when there is a space in the file path.

然后,您可以在 utils 文件的顶部放置一个 if 语句,并将 display_pathjoin 定义为无操作和os.path.join 如果不在 Windows 上.

You could then put an if statement at the top of your utils file and define display_path and join as a no-op and as os.path.join respectively if not on Windows.