为什么os.path.join不使用os.path.sep或os.sep? [英] Why not os.path.join use os.path.sep or os.sep?

查看:142
本文介绍了为什么os.path.join不使用os.path.sep或os.sep?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道,Windows接受"\""/"作为分隔符. 但是在python中,使用了"\".例如,调用os.path.join("foo","bar")'foo\\bar'将被返回.令人讨厌的是,这里有一个转义字符,因此您不能仅复制路径字符串并将其粘贴到资源管理器位置栏中.

我想知道有什么方法可以使python使用"/"作为默认分隔符,我尝试将os.path.sep和os.sep的值更改为"/",但是os.path.join仍然使用.

什么是正确的方法?

PS:

我只是不明白为什么python在Windows上使用"\"作为默认分隔符,也许旧版本的Windows不支持"/"?

解决方案

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

例如

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

如果要用str.join代替os.path.join,则可以执行此操作(str.join需要一个列表,os.path.join需要*args):

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

也许更好的方法是让Python将所有内容标准化,然后替换,例如:

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

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

然后,您可以在utils文件的顶部放置if语句,并将display_pathjoin分别定义为no-op和os.path.join(如果不是Windows则为).

As we know, windows accept both "\" and "/" as separator. But in python, "\" is used. For example, call os.path.join("foo","bar"), 'foo\\bar' will be returned. What's annoying is that there's an escape character, so you cannot just copy the path string and paste to your explorer location bar.

I wonder is there any way to make python use "/" as default separator, I've tried change the value of os.path.sep and os.sep to "/", but os.path.join still use "\\".

what's the right way?

PS:

I just don't understand why python is using "\" as default separator on windows, maybe old version of windows don't support "/"?

解决方案

Why not define a custom display function?

e.g.

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

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)

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

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

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

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.

这篇关于为什么os.path.join不使用os.path.sep或os.sep?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆