Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why not os.path.join use os.path.sep or os.sep?

Tags:

python

path

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 "/"?

like image 869
ThemeZ Avatar asked Dec 01 '22 23:12

ThemeZ


2 Answers

To answer your question as simply as possible, just use posixpath instead of os.path.

So instead of:

from os.path import join
join('foo', 'bar')
# will give you either 'foo/bar' or 'foo\\bar' depending on your OS

Use:

from posixpath import join
join('foo', 'bar')
# will always give you 'foo/bar'
like image 73
semicolon Avatar answered Dec 05 '22 02:12

semicolon


It is all about how Python detects your os:

# in os.py
if 'posix' in _names:
    ...
    import posixpath as path   

elif 'nt' in _names:
    ...
    import ntpath as path

So, on Windows the ntpath module is loaded. If you check the ntpath.py and posixpath.py modules you'd notice that ntpath.join() is a bit more complex and that is also because of the reason you've mentioned: Windows understands / as a path separator.

Bottomline: although you can use posixpath.join() in Windows (as long as the arguments are in POSIX format), I would not recommend doing it.

like image 42
Zaur Nasibov Avatar answered Dec 05 '22 01:12

Zaur Nasibov