Vasilly.Prokopyev
Vasilly.Prokopyev

Reputation: 874

Using os.path for POSIX Path Operations on Windows

I'm using Paramiko on Windows to access a remote SFTP server. I need to do some work with remote paths like os.path.join, os.path.commonprefix, etc. Since my host platform is Windows, all paths operations come with the \ separator, but I need POSIX-styled paths.

Is there any way to use Python built-in POSIX path operations on Windows?

Upvotes: 10

Views: 12104

Answers (2)

zerocewl
zerocewl

Reputation: 12804

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.

Upvotes: 0

Francesco
Francesco

Reputation: 4250

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>

Upvotes: 17

Related Questions