Using os.path for POSIX Path Operations on Windows Using os.path for POSIX Path Operations on Windows windows windows

Using os.path for POSIX Path Operations on Windows


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:

  • posixpath for UNIX-style paths
  • ntpath for 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 ofthese classes, since they don’t provide any operation that does systemcalls.