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
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ pathlib.html
pathlib โ€” Object-oriented filesystem paths
February 23, 2026 - You cannot instantiate a WindowsPath when running on Unix, but you can instantiate PureWindowsPath. You want to make sure that your code only manipulates paths without actually accessing the OS. In this case, instantiating one of the pure classes may be useful since those simply donโ€™t have any OS-accessing operations. ... PEP 428: The pathlib module โ€“ object-oriented filesystem paths.
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

Windows path to Python path
I wonder is there a better solution on the issue to convert windows path to python path? Yes; simply use pathlib. from pathlib import Path win_path = r"" path_universal = Path(win_path) print("Your Python Path: ", path_universal) The more you use it, the more you regret not knowing about it earlier. It's an awesome piece of kit in the standard library, probably my favourite. More on reddit.com
๐ŸŒ r/learnpython
4
2
February 2, 2022
python - How to resolve a server path on Windows with Pathlib? - Stack Overflow
So I have a path to a server that looks like \\foo\bar\baz I am trying to convert this to a Path object with Python's pathlib library with something like Path('\\foo').joinpath('bar').joinpath('... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Convert WindowsPath to String - Stack Overflow
I think this is because I am trying to glob a Windows File Path when I need to glob a string. Is there a way that I can convert WindowsPath to string so that I can glob all the files into one list? ... Which line of code? You have more info than we do. ... try type(parent_dir), I think it is WindowsPath (not str). + operation failing due to different types. ... Two things to consider: pathlib ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
pathlib.Path.absolute() mishandles drive-relative Windows paths
Windows has one current directory per drive, and supports drive-relative paths like 'X:' and 'X:foo.txt'. This makes a conversion from relative to absolute paths more complicated th... More on github.com
๐ŸŒ github.com
1
January 6, 2023
๐ŸŒ
Real Python
realpython.com โ€บ python-pathlib
Python's pathlib Module: Taming the File System โ€“ Real Python
January 11, 2025 - Itโ€™s possible to ask for a WindowsPath or a PosixPath explicitly, but youโ€™ll only be limiting your code to that system without gaining any benefits. A concrete path like this wonโ€™t work on a different system: ... >>> import pathlib >>> pathlib.WindowsPath("test.md") Traceback (most recent call last): ...
๐ŸŒ
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

๐ŸŒ
Medium
medium.com โ€บ @favourphilic โ€บ a-simple-guide-to-pathlib-python-8c6d8fc3061
A simple Guide to Pathlib Module | by Victor Jokanola | Medium
April 18, 2023 - Therefore,the type of path will be a PureWindowPath. from pathlib import PurePath p = PurePath('subdir1')print(p)PureWindowsPath('subdir1') Use the PureWindowspath if you are working on your local windows machine, because it represents the windows file system path.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ pathlib-module-in-python
Pathlib Module in Python - GeeksforGeeks
2 weeks ago - Example: This code imports WindowsPath class and creates a concrete path object using WindowsPath('C:/Program Files/') which represents a Windows-style file system path. ... from pathlib import WindowsPath obj = WindowsPath('C:/Program Files/') # Instantiate WindowsPath class print(obj)
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ how-to-use-pathlib-module-in-python
Python Path โ€“ How to Use the Pathlib Module with Examples
May 10, 2022 - The same applies to WindowsPath() since you are running on a different operating system โ€“ so instantiating it will raise an error. Since the concrete path is the subclass of the pure path, you can do everything with concrete paths using the PurePath() properties. This means that we can use, for example, the .with_suffix property to add a suffix to a concrete path: In [*]: p = pathlib.Path('/src/goo/scripts/main') p.with_suffix('.py') Out[*]: PosixPath('/src/goo/scripts/main.py')
Find elsewhere
๐ŸŒ
Runebook.dev
runebook.dev โ€บ en โ€บ docs โ€บ python โ€บ library โ€บ pathlib โ€บ pathlib.WindowsPath
python - Pathlib WindowsPath: Common Issues and Cross-Platform Solutions
First off, pathlib is a great module for working with file system paths, offering an object-oriented way to handle them. pathlib.WindowsPath is the specific class used by pathlib when your Python script is running on a Windows operating system.
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ comprehensive-tutorial-on-using-pathlib-in-python-for-file-system-manipulation
How to Use Python's Pathlib (with Examples) | DataCamp
May 22, 2024 - Just like a physical address has ... pathlib allows us to access and manipulate these components using path attributes through dot notation. The root is the topmost directory in a file system. In Unix-like systems, it is represented by a forward slash (/). In Windows, it is typically ...
Top answer
1 of 2
53

As most other Python classes do, the WindowsPath class, from pathlib, implements a non-defaulted "dunder string" method (__str__). It turns out that the string representation returned by that method for that class is exactly the string representing the filesystem path you are looking for. Here an example:

from pathlib import Path

p = Path('E:\\x\\y\\z')
>>> WindowsPath('E:/x/y/z')

p.__str__()
>>> 'E:\\x\\y\\z'

str(p)
>>> 'E:\\x\\y\\z'

The str builtin function actually calls the "dunder string" method under the hood, so the results are exaclty the same. By the way, as you can easily guess calling directly the "dunder string" method avoids a level of indirection by resulting in faster execution time.

Here the results of the tests I've done on my laptop:

from timeit import timeit

timeit(lambda:str(p),number=10000000)
>>> 2.3293891000000713

timeit(lambda:p.__str__(),number=10000000)
>>> 1.3876856000000544

Even if calling the __str__ method may appear a bit uglier in the source code, as you saw above, it leads to faster runtimes.

2 of 2
4

You are right, you need a string when you call glob.glob. In the last line of your code, parent_dir is a pathlib.Path object, which you cannot concatenate with the string '/*fits'. You need to explicitly convert parent_dir to a string by passing it to the built-in str function.

The last line of your code should thus read:

fspec = glob.glob(str(parent_dir)+'/*fits')

To illustrate further, consider this example:

>>> from pathlib import Path
>>> path = Path('C:\\')
>>> path
WindowsPath('C:/')
>>> str(path)
'C:\\'
>>>
๐ŸŒ
GitHub
github.com โ€บ python โ€บ cpython โ€บ issues โ€บ 100809
pathlib.Path.absolute() mishandles drive-relative Windows paths ยท Issue #100809 ยท python/cpython
January 6, 2023 - >>> import os, nt, pathlib >>> os.chdir('Z:/build') >>> os.chdir('C:/') >>> os.path.abspath('Z:') 'Z:\\build' >>> nt._getfullpathname('Z:') 'Z:\\build' >>> pathlib.Path('Z:').absolute() WindowsPath('Z:')
Author ย  barneygale
๐ŸŒ
Readthedocs
pathlib.readthedocs.io
pathlib โ€” pathlib 1.0.1 documentation
The string representation of a path is the raw filesystem path itself (in native form, e.g. with backslashes under Windows), which you can pass to any function taking a file path as a string:
๐ŸŒ
Mimo
mimo.org โ€บ glossary โ€บ python โ€บ pathlib
Python Pathlib Module: Syntax, Usage, and Examples
Pathlib also exposes โ€œpureโ€ path classes that handle path semantics without touching the filesystem: purepath โ†’ PurePath base class for path operations ... Use these when you just need to join, split, or compare paths independent of the host OS. For actual filesystem work, prefer Path() (which yields a platform-specific concrete class like PosixPath on Linux). Some codebases and tutorials reference windowpath to mean Windows-flavored paths; in pathlib the concrete classes are WindowsPath (Windows) and PosixPath (Unix-like).
๐ŸŒ
Ethz
compenv.phys.ethz.ch โ€บ python โ€บ ecosystem_3 โ€บ 13_pathlib
pathlib โ€” Basics of Computing Environments for Scientists
PROJECT_DIR = Path("path") / Path("to") / Path("project") PROJECT_DIR = Path("path", "to", "project") PROJECT_DIR = Path("path").joinpath("to", "project") ... Use raw string literals for Windows paths.
๐ŸŒ
Read the Docs
python.readthedocs.io โ€บ en โ€บ latest โ€บ library โ€บ pathlib.html
11.1. pathlib โ€” Object-oriented filesystem paths
November 15, 2017 - You cannot instantiate a WindowsPath when running on Unix, but you can instantiate PureWindowsPath. You want to make sure that your code only manipulates paths without actually accessing the OS. In this case, instantiating one of the pure classes may be useful since those simply donโ€™t have any OS-accessing operations. ... PEP 428: The pathlib module โ€“ object-oriented filesystem paths.
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
How to Use pathlib in Python | note.nkmk.me
February 9, 2024 - pathlib.Path() creates an instance of a class according to the execution environment. For example, it creates a PosixPath instance on Unix-like systems and a WindowsPath on Windows.
๐ŸŒ
Snyk
snyk.io โ€บ advisor โ€บ pathlib โ€บ functions โ€บ pathlib.purewindowspath
How to use the pathlib.PureWindowsPath function in pathlib | Snyk
April 19, 2023 - If we'll ever find one, then it's time to # implement more serious batch interpreter instead. new_path = winpathlib.to_posix_path(this_line[1]) assert new_path, 'error processing .bat ' + \ 'file: no directory named ' + \ '{}'.format(this_line[1]) win_path = pathlib.PureWindowsPath(first_word) exe = win_path.parts[-1] if exe.lower() in ('dosbox', 'dosbox.exe'): return new_path, this_line[1:] assert False, 'error processing .bat file (line {})'.format(line_num) return None, []