5

I've been searching for what seems like hours for how to get a real path in string format from a pathlib.PosixPath using pathlib.

The only solution I can find is this:

str(myPathObject.resolve())

This seems messy. Am I missing something or is this only solution that exists?

Edit:

To clarify, this is giving me a filepath /opt/digglerz/projects of type string, which is what i want. This seems a long way to do this, is there no better way?

Preston
  • 7,399
  • 8
  • 54
  • 84

2 Answers2

2

resolve() is a good idea, but the literal casting with str indeed seems a bit messy. I would go with built-in methods like as_posix() or as_uri() depending on what you want.

Understand that the concept of "real path" as you call it may be different in different situations and on different platforms.

Hope this helps!

Bart Van Loon
  • 1,430
  • 8
  • 18
  • Looking at the [source code](https://github.com/python/cpython/blob/3.7/Lib/pathlib.py#L713) reveals that `as_posix()` just returns `str(self).replace(f.sep, '/')`. – mkrieger1 Jun 06 '19 at 12:25
  • 1
    Why would you use `as_posix()` to convert a path to string? If you don't want a posix path, don't use `as_posix()`. Just use `str`. – Aran-Fey Jun 06 '19 at 12:32
1

Since 3.6 the correct way to convert a Path object back into a string seems to be:

os.fspath(path)

https://docs.python.org/3/library/os.html#os.fspath

Grumbel
  • 6,585
  • 6
  • 39
  • 50