Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert WindowsPath to PosixPath

I am using pathlib to manage my paths in my Python project using the Path class.

When I am using Linux, everything works fine. But on Windows, I have a little issue.

At some point in my code, I have to write a JavaScript file which lists the references to several other files. These paths have to be written in POSIX format. But when I do str(my_path_instance) on Windows, The path is written in Windows format.

Do you know a simple way to convert a WindowsPath to a PosixPath with pathlib?

like image 985
graille Avatar asked Feb 13 '19 13:02

graille


2 Answers

pathlib has an as_posix method to convert from Windows to POSIX paths:

pathlib.path(r'foo\bar').as_posix()

Apart from this, you can generally construct system-specific paths by calling the appropriate constructor. The documentation states that

You cannot instantiate a WindowsPath when running on Unix, but you can instantiate PureWindowsPath. [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, use the PureWindowsPath class and convert via as_posix:

>>> pathlib.PureWindowsPath(r'a\b').as_posix()
'a/b'
like image 92
Konrad Rudolph Avatar answered Sep 29 '22 13:09

Konrad Rudolph


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

.

enter image description here

like image 24
Tamara Koliada Avatar answered Sep 29 '22 12:09

Tamara Koliada