Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I output paths with forward slashes with pathlib on Windows?

Tags:

python

pathlib

How can I use pathlib to output paths with forward slashes? I often run into programs that accept paths only with forward slashes, but I can't figure out how to make pathlib do that for me.

from pathlib import Path, PurePosixPath

native = Path('c:/scratch/test.vim')
print(str(native))
# Out: c:\scratch\test.vim
# Backslashes as expected.

posix = PurePosixPath(str(native))
print(str(posix))
# Out: c:\scratch\test.vim
# Why backslashes again?

posix = PurePosixPath('c:/scratch/test.vim')
print(str(posix))
# Out: c:/scratch/test.vim
# Works, but only because I never used a Path object

posix = PurePosixPath(str(native))
print(str(posix).replace('\\', '/'))
# Out: c:/scratch/test.vim
# Works, but ugly and may cause bugs

PurePosixPath doesn't have unlink, glob, and other useful utilities in pathlib, so I can't work exclusively with it. PosixPath throws NotImplementedError on Windows.

A practical use case where this is necessary: zipfile.ZipFile expects forward slashes and fails to match paths when given backslashes.

Is there some way to request a forward-slashed path from pathlib without losing any pathlib functionality?

like image 674
idbrii Avatar asked Dec 30 '25 00:12

idbrii


1 Answers

Use Path.as_posix() to make the necessary conversion to string with forward slashes.

like image 89
Ben Y Avatar answered Dec 31 '25 15:12

Ben Y



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!