Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you find the first element of a path?

I just downloaded Python 3.4 and I'm wondering how you would go about finding the first directory of a relative path? I.e. given the path a/b/c/d I would like to print a.

The closest I've gotten is:

from pathlib import Path
print(list(Path('a/b/c/d').parents)[-2])

or

p = Path('a/b/c/d')
print(p.parents[len(p.parents) - 2])

in both cases the -2 part is a bit magical. I've read the docs and the PEP, and haven't found any better way.. did I miss something obvious?

like image 476
thebjorn Avatar asked Mar 23 '14 16:03

thebjorn


People also ask

How do I find Python path?

In order to obtain the Current Working Directory in Python, use the os. getcwd() method. This function of the Python OS module returns the string containing the absolute path to the current working directory.

How do I get the base of a directory in Python?

dirname() method in Python is used to get the directory name from the specified path. Parameter: path: A path-like object representing a file system path. Return Type: This method returns a string value which represents the directory name from the specified path.

What does os path Basename do?

path. basename() method in Python is used to get the base name in specified path.

How do you split a path in Python?

path. split() method in Python is used to Split the path name into a pair head and tail. Here, tail is the last path name component and head is everything leading up to that.


2 Answers

Use parts attribute:

>>> from pathlib import Path
>>> Path('a/b/c/d').parts
('a', 'b', 'c', 'd')
>>> Path('a/b/c/d').parts[0]
'a'
like image 53
falsetru Avatar answered Sep 17 '22 00:09

falsetru


Path.parts is what you need.

p = Path("a/b/c/d")
print(p.parts[0])
like image 28
Graeme Stuart Avatar answered Sep 17 '22 00:09

Graeme Stuart