Pathlib in Python

I found pathlib standard library in Python just recently. It is a full set of classes, methods, properties and operators that make it very easy to work with files, directories and paths in operating system-independent way. You all do remember that not all filesystems use / (slash) as the path separator…?

I had a specific task at hand: reading a configuration file from the user’s home directory. I could have used the os standard library and fetch the HOME environment variable and then concatenate the HOME value with “/ipam.cfg” but here is what I did:

>>> from pathlib import Path
>>> Path.cwd() # where I am currently
>>> Path.home() # what is my home directory
>>> config_file = Path.home() / "ipam.cfg"
>>> print(config_file)

Note the use of “/” operator here: It has been specified in the Path class and it is used to combine the path components.

What is nice is that it is OS-independent. See the same in Windows:

>>> from pathlib import Path
>>> Path.cwd()
>>> Path.home()
>>> print(Path.home() / "ipam.cfg")

The reverse operations are possible as well without hardcoding slashes:

>>> config_file
('/', 'home', 'markku', 'ipam.cfg')

The above means that you can access the components of the path object safely without manual string parsing operations.

And this was just scratching the surface of the pathlib library, you may find also other useful features for your applications.

So: Please do not try to handle your paths manually by concatenating or splitting by slashes (forward slashes or backslashes) but check pathlib out.

Also, if you are writing functions or methods that currently take path arguments as strings, make sure to also enable and test handling of Path classes introduced in pathlib.

Leave a Reply