10

I use pathlib to match all files recursively to filter the files based on their content. Then I would like to find what is the top level of the folder of this file. Assume the following. I have a file in the folder:

a/b/c/file.log

I do the search from the level a:

for f in path_data.glob("**/*"):
    if something inside file f:
         # I would like to get in what folder this file is, i.e. 'b'

I now that I can get all parents levels using:

  • f.parents would give me b/c
  • f.parent would give me c
  • f.name would give me file.log

But how could I get b?

Just to precise: the number of levels where the file is stored is not known.

UPD: I know I could do it with split, but I would like to know if there is a proper API to do that. I couldn't find it.

desa
  • 1,240
  • 12
  • 31

1 Answers1

21

The question was asked a while ago, but didn't quite get the attention. Nevertheless, I still would publish the answer:

f.parts[0]
desa
  • 1,240
  • 12
  • 31