How to Get a Path with Forward Slashes in Python with as_posix
On Windows, a path prints with backslashes, reports\2026\march.csv; on macOS and Linux, with forward slashes. When a log line or a message should look the same everywhere, as_posix() gives the path as text with forward slashes on every system. This guide compares the two forms on Python 3.15.2.
Syntax
<text> = <path>.as_posix()
| Part | What it means |
|---|---|
<path> | A pathlib path, such as Path("reports") / "2026" |
<text> | The path as a string, with / between its parts |
The pathlib reference says as_posix will "Return a string representation of the path with forward slashes (/)".
The Example
The script builds the same path twice: once as a normal Path on this Mac, and once as a PureWindowsPath, which follows Windows' rules on any computer. It prints each path as it is and with as_posix().
Prerequisites
- uv and Python 3. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with
uv init.
Step 1: Write the Script
from pathlib import Path, PureWindowsPath
report = Path("reports") / "2026" / "march.csv"
print(report)
print(report.as_posix())
windows_report = PureWindowsPath("reports") / "2026" / "march.csv"
print(windows_report)
print(windows_report.as_posix())

Step 2: Run It
uv run python as_posix.py
reports/2026/march.csv
reports/2026/march.csv
reports\2026\march.csv
reports/2026/march.csv

On the Mac, the path prints with forward slashes either way. The Windows path prints with backslashes, but as_posix() gives reports/2026/march.csv, the same text as on the Mac. The command works unchanged in PowerShell.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Passing the as_posix() text on to open() and other file functions | You turn a path into plain text for no gain | Pass the Path object itself to file functions; keep as_posix() for text that people read |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
A log shows data\raw\file.csv on Windows and data/raw/file.csv elsewhere | The path is printed with str() | Print path.as_posix() |
FAQ
Do I need PureWindowsPath in real code?
Usually not. Path already follows the rules of the computer it runs on. The pathlib reference suggests pure paths "If you want to manipulate Windows paths on a Unix machine (or vice versa)", as this example does.
Is the result a Path or text?
Text: as_posix() returns a str.
Conclusion
as_posix() turned both paths into reports/2026/march.csv, even the Windows one that prints with backslashes. Use it wherever a path ends up in text that people read.
Additional Resources
- PurePath.as_posix — the pathlib reference.
- Pure paths —
PureWindowsPathandPurePosixPath.
