Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get folder name, in which given file resides, from pathlib.path?

Is there something similar to os.path.dirname(path), but in pathlib?

like image 784
trainset Avatar asked Feb 18 '16 18:02

trainset


People also ask

What does Pathlib path return?

parts : returns a tuple that provides access to the path's components. name : the path component without any directory. parent : sequence providing access to the logical ancestors of the path. stem : final path component without its suffix.

What does Pathlib path do?

The pathlib is a Python module which provides an object API for working with files and directories. The pathlib is a standard module. Path is the core object to work with files.

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

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.


1 Answers

It looks like there is a parents element that contains all the parent directories of a given path. E.g., if you start with:

>>> import pathlib >>> p = pathlib.Path('/path/to/my/file') 

Then p.parents[0] is the directory containing file:

>>> p.parents[0] PosixPath('/path/to/my') 

...and p.parents[1] will be the next directory up:

>>> p.parents[1] PosixPath('/path/to') 

Etc.

p.parent is another way to ask for p.parents[0]. You can convert a Path into a string and get pretty much what you would expect:

>>> str(p.parent) '/path/to/my' 

And also on any Path you can use the .absolute() method to get an absolute path:

>>> os.chdir('/etc') >>> p = pathlib.Path('../relative/path') >>> str(p.parent) '../relative' >>> str(p.parent.absolute()) '/etc/../relative' 

Note that os.path.dirname and pathlib treat paths with a trailing slash differently. The pathlib parent of some/path/ is some:

>>> p = pathlib.Path('some/path/') >>> p.parent PosixPath('some') 

While os.path.dirname on some/path/ returns some/path:

>>> os.path.dirname('some/path/') 'some/path' 
like image 162
larsks Avatar answered Sep 22 '22 15:09

larsks