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 "/"?
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'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With