idbrii
idbrii

Reputation: 11946

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

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?

Upvotes: 15

Views: 8079

Answers (1)

Ben Y
Ben Y

Reputation: 1023

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

Upvotes: 27

Related Questions