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?
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.
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.
path. basename() method in Python is used to get the base name in specified path.
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.
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'
Path.parts is what you need.
p = Path("a/b/c/d")
print(p.parts[0])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With