-2

I have a tree of directories that in the end of the each directory will always be 2 files, one as suffix ".txt" and one will always be ".jpg", for example: "rootFolder/a/a.txt", "rootFolder/a/b.jpg" "rootFolder/b/c/a.txt", "rootFolder/b/c/b.jpg" and I want that the output will be: ["rootFolder/a", "rootFolder/b/c"]

import pathlib
root = pathlib.Path("/rootFolder")
paths = list(root.rglob("*.txt")) + list(root.rglob("*.jpg"))

this code give me the pathes of the files but i want their parents and i'm pretty sure that i there is one line code that do it but i didn't figure it out.

Dump Eldor
  • 92
  • 1
  • 11

1 Answers1

1

So, just use dirname to remove the filename part of the path, and convert it to a set to remove duplicates:

paths = set([os.path.dirname(p) for p in paths])
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30