Python Tips 7 -A (very) Little Intro to Path Management With Pathlib

in STEMGeeks4 years ago

Python Tips - Path Management With Pathlib

In the os module, you can find a lot of things:

  • the environment variables (os.environ)
  • a basic path management system (os.path.(...))
  • function the current numeric umask and return the previous umask (os.umask(mask))

There is a more conveniant way to manage path, the pathlib package.

Let's import it !

>>>import pathlib

To create a path juste use the pathlib.Path class:

>>>bashrc_path = pathlib.Path("/home/slash/.bashrc")

The real type of bashrc_path will depend on your plateform

Here is the class inheritance diagram :


So how do we use it ?

You can combine two path with this operator: / , here is an exemple.

>>>init_path = pathlib.Path("/home/slash/.bashrc")
>>>bashrc_file_path = pathlib.Path(".bashrc")
>>>bashrc_path = init_path / bashrc_file_path

Parts

You can access the differents parts of a path :

>>> p = pathlib.Path('/usr/bin/python3')
>>> p.parts
('/', 'usr', 'bin', 'python3')

Methods and properties

We will setup the path test_path like shown below for this section:

>>> test_path = pathlib.Path("/home/slash/Documents/rendu.xls")

Root

>>> test_path.root
'/'

Parent

>>> test_path.parent
PurePosixPath('/home/slash/Documents')

Name

This is the name of the file is it's a file

>>> test_path.name
'rendu.xls'

Stem

>>> test_path.stem
'rendu'

This is just a very tiny part of what pathlib is capable, you will find the documentation for Python 3.8.4 here: https://docs.python.org/3/library/pathlib.html?highlight=pathlib#module-pathlib

Pathlib was in Python In The Morning ! You can find the corresponding section here

You made it to the end, bravo! If you have any questions, don't forget to ask. See you next time! If you spot a grammar or vocabulary mistake, please let me know in the comments.

You will be able to find a good part of the articles in this account in this repository.

To go directly to the section you are currently viewing click here.

Latest article in the series Python Tips: Python Tips 6 - Collections : Container Datatype