Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a top level from Path object of pathlib

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.

like image 556
desa Avatar asked Oct 11 '17 12:10

desa


1 Answers

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

f.parts[0]
like image 117
desa Avatar answered Nov 15 '22 01:11

desa