DEV Community

Cover image for python pathlib

python pathlib

・2 min read

With the Python programming language, you can deal with files. Some things you can do with Python are read files, write files, create files and much more.

If you worked with files in Python, you know that dealing with Paths can be quite cumbersome. On top of that paths are written differently on systems like Windows () or Mac (/)

You may be familiar with having to deal with double slashes and the like:

b = "c:\\stuff\\morestuff\\furtherdown\\THEFILE.txt"

Meet the pathlib module, which prevents you from writing code like this.


Pathlib makes working with paths and files in general easier. Instead of those ugly double slashes you can write elegant and readable Python code.
To get your home directory:

>>> import pathlib
>>> pathlib.Path.home()

The current working directory:

>>> import pathlib
>>> pathlib.Path.cwd()

You can simply add slashes for subdirectories

>>> pathlib.Path.home() / 'Desktop' / 'pama'

To define a filepath you can do this:

>>> filename = pathlib.Path.home() / 'Desktop' / 'files' / 'test.txt'
>>> filename

So you can use that path (filename) to read files as you would normally do:

>>> filename = pathlib.Path.home() / 'rdp.txt'
>>> with open(filename, mode='r') as f:
...     data = f.readlines()
>>> data

You can even read files with one liner:

data = pathlib.Path(pathlib.Path.home() / 'rdp.txt').read_text()

To get the extension, name or parent of a path is also super easy:

>>> path = pathlib.Path.home() / 'Desktop' / 'files' / 'test.txt'
>>> path
>>> path.parent
>>> path.suffix
>>> path.stem

Related links:

Discussion (0)