0

Let's say I have a Path object like so:

from pathlib import Path
path = Path('/Users/Me/Desktop/Media/Pictures')

On posix systems, this returns a PosixPath object, and on Windows, a WindowsPath object.

Is there a nice, build-in Pythonic way to get this natively using pathlib?

>>> segments
['Users', 'Me', 'Desktop', 'Media', 'Pictures']

(Or if not a list, a generator is fine, too).

I know I could do this, but I don't like that it relies on str type conversion, and though I can't test this on Windows, I'm not confident it will handle backslash escaping well:

[x for x in str(path).split(pathlib.os.sep)]
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
brandonscript
  • 68,675
  • 32
  • 163
  • 220
  • 1
    Are you looking for [`path.parts`](https://docs.python.org/3/library/pathlib.html#accessing-individual-parts)? – jonrsharpe Apr 06 '21 at 16:51
  • Do you know how many times I've read the docs, and missed that? Sigh. Thank you! If you want to post an answer, I'll accept. – brandonscript Apr 06 '21 at 16:52
  • 2
    For future visitors, the answer in the linked duplicate question that specifically answers this one is https://stackoverflow.com/a/38741379/1214800 – brandonscript Apr 06 '21 at 17:13
  • @jonrsharpe if you're going to mark this as a dup, please at least leave in the direct link to the answer to this specific question in the body, so that future visitors don't have to search for it. The dup is very old, and there a lot of irrelevant answers, and lots of folks don't read the comments. – brandonscript Apr 06 '21 at 18:11

0 Answers0