CertGrid CertGrid
Hands-on Lab·Python Automation for IT

Python pathlib and Filesystem Operations

Automation is mostly files. pathlib makes a path an object rather than a string, which means the filename's parts have names, joining uses / instead of string concatenation, and reading a whole file is one call. It also contains the single most valuable line in this domain: Path(__file__).resolve().parent, which is what stops a scheduled script losing track of its own data directory.

Files and Data Formats Guide 10 of 39 Beginner

pathlib has been in the standard library since Python 3.4 and is the recommended interface. Path.with_stem arrived in 3.9 and unlink(missing_ok=True) in 3.8; both are used here. os.path still works and still appears in older code.

Everything on this page runs on the control node. Any machine with Python 3 will do.
Server NameIP AddressOSRolesCPURAMHDD
RUNNER01192.168.0.27Ubuntu 26.04 LTSControl node - every script in this path runs here2 Core4 GB50 GB

This guide includes

Use this because automation is mostly files. This matters because a scheduled script starts in a directory you did not choose - and one line makes every relative path in it survive that.

Before you start

  1. A path is an object, not a string

  2. Joining with a slash

  3. The questions you ask before touching anything

  4. The one line that survives a scheduler

  5. Read and write, in one call each

  6. Making and removing directories

  7. Finding files

  8. resolve and absolute are not the same

  9. What domain 2 asks about this

Official sources