8

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?

idbrii
  • 10,975
  • 5
  • 66
  • 107
  • Why do you care? The only place this can cause bugs is if you generate command lines for a batch file. The cmd shell insists on backslashes. Every Win32 API will accept either one. – Tim Roberts Jul 13 '21 at 21:37
  • You could, of course, subclass `Path` and provide your own `__str__` function. – Tim Roberts Jul 13 '21 at 21:39
  • Just in case, here is another ugly way: `"/".join(native.parts)`. Perhaps a little bit less ugly of buggy. Or not. It depends. – Yuri Khristich Jul 13 '21 at 22:32

1 Answers1

17

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

cod3monk3y
  • 9,508
  • 6
  • 39
  • 54
Ben Y
  • 913
  • 6
  • 18