As pointed out in the documentation (2nd note)
... you can also import and use the individual modules if you want to manipulate a path that is always in one of the different formats. They all have the same interface:
posixpathfor UNIX-style pathsntpathfor Windows paths
So you could import posixpath and use it as os.path
>>> import posixpath
>>> posixpath.join
<function join at 0x025C4170>
>>> posixpath.join('a','b')
'a/b'
>>> posixpath.commonprefix
<function commonprefix at 0x00578030>
In my opinion pathlib.PurePosixPath is the way to go (as already commented by phoenix).
E.g.:
>>> import pathlib
>>> pathlib.PurePosixPath('a', 'b')
PurePosixPath('a/b')
>>> str(pathlib.PurePosixPath('a', 'b'))
'a/b'
From the depending docs:
class pathlib.PurePosixPath(*pathsegments)
A subclass of PurePath, this path flavour represents non-Windows filesystem paths:
>>> PurePosixPath('/etc') PurePosixPath('/etc')pathsegments is specified similarly to PurePath.
class pathlib.PureWindowsPath(*pathsegments)
A subclass of PurePath, this path flavour represents Windows filesystem paths:
>>> PureWindowsPath('c:/Program Files/') PureWindowsPath('c:/Program Files')pathsegments is specified similarly to PurePath.
Regardless of the system you’re running on, you can instantiate all of these classes, since they don’t provide any operation that does system calls.
pathlib.*Path has an as_posix method to convert from Windows to POSIX paths on Windows:
>>> pathlib.Path(r'a\b').as_posix()
'a/b'
Apart from this, you can generally construct system-specific paths by calling the appropriate constructor. The documentation states that
You cannot instantiate a
WindowsPathwhen running on Unix, but you can instantiatePureWindowsPath. [or vice versa]
So use the Pure* class constructor:
str(pathlib.PurePosixPath(your_posix_path))
However, this won’t do what you want if your_posix_path contains backslashes, since \ (= Windows path separator) is just a regular character as far as POSIX is concerned. So a\b is valid POSIX filename, not a path denoting a file b inside a directory b, and PurePosixPath will preserve this interpretation:
>>> str(pathlib.PurePosixPath(r'a\b'))
'a\\b'
To convert Windows to POSIX paths regardless of platform your code is running on, use the PureWindowsPath class and convert via as_posix:
>>> pathlib.PureWindowsPath(r'a\b').as_posix()
'a/b'
Python pathlib if you want to manipulate Windows paths on a Unix machine (or vice versa) - you cannot instantiate a WindowsPath when running on Unix, but you can instantiate PureWindowsPath/PurePosixPath
.
