Why Not Os.path.join Use Os.path.sep Or Os.sep?
Solution 1:
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'
Solution 2:
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.
Solution 3:
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.
Solution 4:
I would not recommend doing this.
Note that while windows does accept slash /
as path seperator also, it has a different meaning in some contexts.
It's treated as relative path using cd
, for example:
Command line:
c:\Users\YourUser> cd /FooBar
c:\FooBar
Here, /
substitutes the drive letter.
Also, I don't see a problem at all with copying the strings, since if you print
the string, the string is displayed as you wish:
Python interpreter:
>>> import os
>>> print os.path.join("c:\", "foo","bar")
c:\foo\bar
>>>
Solution 5:
I don't have enough reputation to comment, but the above answer is incorrect.
Windows has a concept of working directory and working drive. /
is treated as absolute path on your current working drive, since Windows has no concept of single root. In the above example cd /FooBar
goes to C:\foobar
because the working drive is C:, not because C: is "root" drive or somehow special.
Here's an example:
C:\Users\user> cd /
C:\> d:
D:\> cd /Users
The system cannot find the path specified.
D:\> mkdir test
D:\> cd test
D:\test> cd c:/Users
D:\test> cd /
D:\> cd test
D:\test> c:
C:\Users\> d:
D:\test>
Post a Comment for "Why Not Os.path.join Use Os.path.sep Or Os.sep?"