2

There has been multiple discussions about the issue when dealing with trailing slashes in pathlib.Path, on Unix systems in particular such as https://bugs.python.org/issue21039 and https://bugs.python.org/issue39140.

Given the pathlib.Path constructed from a string, I wonder what would be the best way to make sure a trailing slash is preserved in the Path object the same way the os module does it?

>>> os.path.dirname("/a/b/")
'/a/b'
>>> os.path.dirname("/a/b")
'/a'

os module understands the difference between "/a/b/" and "/a/b", but pathlib doesn't:

>>> Path("/a/b/").parent
PosixPath('/a')

Is there any way to be able to differentiate between paths that are pointing to a file (without a trailing slash) and to a directory (that has a trailing slash)? Or I'd have to switch to using os module in this particular case?

If it's not possible, what would be a reasonable workaround to take advantage of pathlib and deal with the trailing slash issue?

Alex Tereshenkov
  • 3,340
  • 8
  • 36
  • 61

1 Answers1

1

This looks like a low-level path manipulation, I would go with the os module (as suggested by the pathlib documentation)

This would add the trailing slash, OS independently:

os.path.join(os.path.abspath("/a/b/"), "")
UgurZCifci
  • 46
  • 8