Skip to main content

How to Get a Path with Forward Slashes in Python with as_posix

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

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​

Syntax
<text> = <path>.as_posix()
PartWhat 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​

as_posix.py
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())

The as_posix.py script in a macOS-style code window: a Path and a PureWindowsPath built from reports, 2026 and march.csv, each printed as it is and with as_posix().

Step 2: Run It​

Terminal
uv run python as_posix.py
Output
reports/2026/march.csv
reports/2026/march.csv
reports\2026\march.csv
reports/2026/march.csv

The terminal after uv run python as_posix.py: two lines with forward slashes for the Mac path, then reports\2026\march.csv with backslashes and its forward-slash version.

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​

MistakeWhat happensDo this instead
Passing the as_posix() text on to open() and other file functionsYou turn a path into plain text for no gainPass the Path object itself to file functions; keep as_posix() for text that people read

Troubleshooting​

SymptomLikely causeFix
A log shows data\raw\file.csv on Windows and data/raw/file.csv elsewhereThe 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​