pathlib is an OO library, not a communication protocol. Just send strings.

Windows can handle paths with forward slashes just fine, and both pathlib and os.path can normalise such paths for you. You probably want to normalise paths in your protocol to use POSIX path separators (forward slashes).

You can convert relative Windows paths to POSIX paths using pathlib.PurePosixPath(), for example:

>>> from pathlib import Path, PurePosixPath
>>> Path('relative\path\on\windows')
WindowsPath('relative\path\on\windows')
>>> PurePosixPath(_)
PurePosixPath('relative/path/on/windows')
>>> str(_)
'relative/path/on/windows'

If your server receives a relative paths using Windows conventions, use PureWindowsPath() to convert it to a pathlib object, then pass that to Path() to convert:

>>> from pathlib import Path, PureWindowsPath
>>> received = 'relative\path\on\windows'
>>> PureWindowsPath(received)
PureWindowsPath('relative/path/on/windows')
>>> Path(_)
PosixPath('relative/path/on/windows')

If you keep paths as strings, then you can use str.replace(os.altsep, os.sep) to achieve the same on the Windows side before sending:

>>> import os
>>> p = 'relative\path\on\windows'
>>> p.replace(os.altsep, os.sep)
'relative/path/on/windows'

and you can always just use relative_path.replace('\\', os.sep) to force the issue.

Answer from Martijn Pieters on Stack Overflow
🌐
Reddit
reddit.com β€Ί r/learnpython β€Ί windows path to python path
r/learnpython on Reddit: Windows path to Python path
February 2, 2022 -

I have been searching the web for a solution without a result.
I made this small script that can be used. Feel free to use it.
I wonder is there a better solution on the issue to convert windows path to python path?

"""
A path, in Windows "C:\Folder" . in Python it is "C:/Folder".
In Python the "\" character can get interpreted as the ESCAPE character.
When an 'r' or 'R' prefix is present, a character following a backslash is
included in the string without change, and all backslashes are left in the string.
"""
def main():
# - YOUR INPUT - IMPORTANT: keep the r in front of path string here.
win_path = r"<TYPE YOUR PATH HERE>"
# Call function to convert from windows to Python path.
path_py = py_path(win_path)
print("Your Python Path: ", path_py)

def py_path(win_path):
python_path = "" # The result of this script.
# Convert to ASCII list
ascii_values_list = []
for character in win_path:
ascii_values_list.append(ord(character))
# Replace all ASCII values for "\" (=92) with value for "/" (=47).
for i in range(0, len(ascii_values_list)):
if ascii_values_list[i] == 92:
ascii_values_list[i] = 47
path_py = "" # Convert ASCII list to string
for val in ascii_values_list:
path_py = path_py + chr(val)

if path_py[-1] != "/": # Add "/" at end of path if needed.
path_py = path_py + "/"
return path_py

if __name__ == "__main__":
main() # Script goes there.

# EOF

Top answer
1 of 2
18

pathlib is an OO library, not a communication protocol. Just send strings.

Windows can handle paths with forward slashes just fine, and both pathlib and os.path can normalise such paths for you. You probably want to normalise paths in your protocol to use POSIX path separators (forward slashes).

You can convert relative Windows paths to POSIX paths using pathlib.PurePosixPath(), for example:

>>> from pathlib import Path, PurePosixPath
>>> Path('relative\path\on\windows')
WindowsPath('relative\path\on\windows')
>>> PurePosixPath(_)
PurePosixPath('relative/path/on/windows')
>>> str(_)
'relative/path/on/windows'

If your server receives a relative paths using Windows conventions, use PureWindowsPath() to convert it to a pathlib object, then pass that to Path() to convert:

>>> from pathlib import Path, PureWindowsPath
>>> received = 'relative\path\on\windows'
>>> PureWindowsPath(received)
PureWindowsPath('relative/path/on/windows')
>>> Path(_)
PosixPath('relative/path/on/windows')

If you keep paths as strings, then you can use str.replace(os.altsep, os.sep) to achieve the same on the Windows side before sending:

>>> import os
>>> p = 'relative\path\on\windows'
>>> p.replace(os.altsep, os.sep)
'relative/path/on/windows'

and you can always just use relative_path.replace('\\', os.sep) to force the issue.

2 of 2
1

.as_posix() is way forward.

from pathlib import Path

p = Path('./my_dir/my_file.txt')
print(p)
# my_dir\my_file.txt
print(p.as_posix())
# my_dir/my_file.txt

Discussions

Using absolute unix paths in windows with python - Stack Overflow
I'm creating an application that stores blob files into the hard drive, but this script must run in both Linux and Windows, the issue is that I want to give it an absolute path from the filesystem ... More on stackoverflow.com
🌐 stackoverflow.com
Normalizing Path between Windows and macOS/Linux
First, if you're already including the full path there's no reason to use Path.resolve unless you expect to have symbolic links. Second, avoid using hard-coded drive letters in cross-platform code. If this is something in the user directory, you could use Path.home() as an anchor and build the rest from there, or you could do Path(__file__).parent to use the script's directory as an anchor. Unfortunately I can't be more specific as there's no contextual meaning in your "secret" filepath. More on reddit.com
🌐 r/learnpython
5
1
August 26, 2021
linux - Python script for changing windows path to unix path - Stack Overflow
I want a script where I can paste a windows path as argument, and then the script converts the path to unix path and open the path using nautilus. I want to be able to use the script as follows: More on stackoverflow.com
🌐 stackoverflow.com
Windows Path 2 Python Path
I wonder is there a better solution on the issue to convert windows path to python path? If you're using an up to date Python 3, none of this is needed. Python handles Windows paths internally. It is only an issue if you hard code a path within the program, in which case you can use "\\" instead of "\" (or "/" as in your code) when writing out the path as a string. If you receive a valid path with single backslashes to store as a variable and do not manipulate it, it will work fine when passed along as a variable. Even the last bit about "/" at the end of the path (if the path is a folder) is not required on Windows, though this is required on Linux if you do not want to accidentally rename your files and folders. More on reddit.com
🌐 r/learnpython
8
3
February 2, 2022
🌐
PyPI
pypi.org β€Ί project β€Ί wsl-path-converter
wsl-path-converter Β· PyPI
Convert between Linux and Windows path in WSL (Windows Subsystem for Linux).
      Β» pip install wsl-path-converter
    
Published Β  Aug 05, 2019
Version Β  0.3.1
🌐
Pythondex
pythondex.com β€Ί convert-windows-path-to-linux-in-python
Convert Windows Path To Linux In Python - Pythondex
January 31, 2024 - So it is important to convert them to their operating system suitable path, In this article you are exactly going to see how to convert windows path linux path in python. ... Above are the examples of how windows and linux path as you can see it uses different backslashes so let’s see how to convert them. from pathlib import Path windows_path = r'C:\Users\JohnDoe\Documents\example.txt' linux_path = Path(windows_path).as_posix() print(linux_path)
🌐
Medium
medium.com β€Ί @ageitgey β€Ί python-3-quick-tip-the-easy-way-to-deal-with-file-paths-on-windows-mac-and-linux-11a072b58d5f
Python 3 Quick Tip: The easy way to deal with file paths on Windows, Mac and Linux | by Adam Geitgey | Medium
January 31, 2018 - To use it, you just pass a path or filename into a new Path() object using forward slashes and it handles the rest: ... You should use forward slashes with pathlib functions. The Path() object will convert forward slashes into the correct kind ...
🌐
Herongyang
herongyang.com β€Ί Python β€Ί pathlib-Path-for-Both-Linux-and-Windows.html
"pathlib.Path" - Path for Both Linux and Windows
>>> from pathlib import Path # A PosixPath object for "/Users/Herong" on Unix/Linux >>> p = Path('/Users/Herong') >>> p PosixPath('/Users/Herong') >>> str(p) '/Users/Herong' # A WindowsPath object for "\Users\Herong" on Windows >>> p = Path('/Users/Herong') >>> p PosixPath('/Users/Herong') >>> str(p) '\\Users\\Herong' Note that Python display "\" as an escape sequence of "\\" on the screen.
Find elsewhere
🌐
Reddit
reddit.com β€Ί r/learnpython β€Ί normalizing path between windows and macos/linux
r/learnpython on Reddit: Normalizing Path between Windows and macOS/Linux
August 26, 2021 -

I'm having a bit of difficulty normalizing the between the OS while using the pathlib library. So far, this is what I have when converting a Windows path to macOS/Linux:

from pathlib import Path

directory = "C:\\some1\\some2\\some3\\some4"
directory_1 = Path(directory).resolve() # "/some1/some2/C:\some1\some2\some3\some4 
directory_2 = os.path.normpath(directory) # "/some1/some2/C:\some1\some2\some3\some4 

Is there a cleaner way of doing this? I've tried multiple ways than even the ones stated above, but it seems fairly difficult other than doing replace('\\', '/'), and even that line of code can be wrong due to the anchor still existing. Any suggestions?

🌐
GitHub
github.com β€Ί consis-tency β€Ί WinLin-Path
GitHub - sjnakib/WinLin-Path: This is a simple Python script that allows you to convert Windows file paths to their corresponding Linux format. It replaces backslashes with forward slashes and converts drive letters to the appropriate Linux format. Β· GitHub
This is a simple Python script that allows you to convert Windows file paths to their corresponding Linux format. It replaces backslashes with forward slashes and converts drive letters to the appropriate Linux format. - sjnakib/WinLin-Path
Author Β  sjnakib
🌐
Python
docs.python.org β€Ί 3 β€Ί library β€Ί pathlib.html
pathlib β€” Object-oriented filesystem paths
February 23, 2026 - Source code: Lib/pathlib/ This module offers classes representing filesystem paths with semantics appropriate for different operating systems. Path classes are divided between pure paths, which pro...
🌐
YouTube
youtube.com β€Ί mo'men ahmed
Python Convert Windows path to Unix path and vice versa - YouTube
How to convert windows path to UNIX in Python.
Published Β  September 8, 2019
Views Β  173
🌐
Reddit
reddit.com β€Ί r/learnpython β€Ί windows path 2 python path
r/learnpython on Reddit: Windows Path 2 Python Path
February 2, 2022 -

I have been searching the web for a solution without a result.
I made this small script that can be used. Feel free to use it.
I wonder is there a better solution on the issue to convert windows path to python path?

"""
A path, in Windows "C:\Folder" . in Python it is "C:/Folder".
In Python the "\" character can get interpreted as the ESCAPE character.
When an 'r' or 'R' prefix is present, a character following a backslash is
included in the string without change, and all backslashes are left in the string.
"""
def main():
# - YOUR INPUT - IMPORTANT: keep the r in front of path string here.
win_path = r"<TYPE YOUR PATH HERE>"
# Call function to convert from windows to Python path.
path_py = py_path(win_path)
print("Your Python Path: ", path_py)

def py_path(win_path):
python_path = "" # The result of this script.
# Convert to ASCII list
ascii_values_list = []
for character in win_path:
ascii_values_list.append(ord(character))
# Replace all ASCII values for "\" (=92) with value for "/" (=47).
for i in range(0, len(ascii_values_list)):
if ascii_values_list[i] == 92:
ascii_values_list[i] = 47
path_py = "" # Convert ASCII list to string
for val in ascii_values_list:
path_py = path_py + chr(val)

if path_py[-1] != "/": # Add "/" at end of path if needed.
path_py = path_py + "/"
return path_py

if __name__ == "__main__":
main() # Script goes there.

# EOF

🌐
Reddit
reddit.com β€Ί r/learnpython β€Ί dealing with paths , when cross platform
r/learnpython on Reddit: Dealing with paths , when cross platform
March 6, 2022 -

How do you deal with paths when cross platform (ie lets say you are on gnu/linux and then want to run your code on windows)

Here is an example

# Below is my directory structure
# cats_dogs contains multiple .wav files
.
β”œβ”€β”€ data
β”‚   β”œβ”€β”€ cats_dogs
β”‚   β”œβ”€β”€ train_test_split.csv
β”‚   └── utils.py
β”œβ”€β”€ model_keras.h5
β”œβ”€β”€ model_wieghts.h5
└── train.ipynb

2 directories, 5 files

Now if have I have to get paths for all the .wav files , while working in train.ipynb i do something like X=glob.glob('data/cats_dogs/*.wav') on linux

but on windows, this does not work , because , it uses "\" instead, so on windows i have to do something like

# I am not sure if this works , i have't tried it , i do not have access to windows # pc , it is something i found on stackoverflow
# But i am pretty sure the solution would be something similar

from pathlib import Path
glob_path = Path(r"data\cats_dogs")
X_path = [str(pp) for pp in glob_path.glob("**/*.wav")]

My Question: is there a way to make it universal , so that it works independent of the os

just to ask for the path , when running, is a solution , but is there any other way , so that the code just runs, without any changes/input needed