CHEATSHEET #2

Five Most Useful Pathlib Operations

Are you still using os.path?

Jenny Lee
The Startup
Published in
3 min readJan 4, 2020

--

Photo by Adam Thomas on Unsplash

0. Basics

One of Python’s most popular standard utility modules, os has provided us with many useful methods for managing a large number of files and directories. But Python 3.4+ gave us an alternative, probably superior, module for this task — pathlib — which introduces the Path class. With this module, we work with path objects instead of path strings and can write much less clunky code.

Below are some of its most useful methods and attributes.

from pathlib import Path>>> Path.home()
PosixPath('/Users/jlee')
>>> Path.cwd()
PosixPath('/Users/jlee/test_dir')

A Path object, instantiated with a path string argument, can be a directory or a file. Use .parent to get to the directory containing the file or its immediately dominating directory if the path itself a directory.

>>> filepath = Path('/Users/jlee/test_dir/test1.txt')>>> filepath.parent
PosixPath('/Users/jlee/test_dir')

This replaces the following more verbose os.path.dirname function:

import os>>> os.path.dirname(os.path.abspath('test1.txt'))…

--

--