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

Question:

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:scratchtest.vim
# Backslashes as expected.

posix = PurePosixPath(str(native))
print(str(posix))
# Out: c:scratchtest.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?

Asked By: idbrii

||

Answers:

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

Answered By: Ben Y
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.