201 — Reading and Writing Files with pathlib

Beginner

Use Python's stdlib pathlib module to read, write, append, rename, delete, and search files on disk — then combine those primitives into a DevOps script that reads a deploy config file and writes a timestamped run log.

Learning Objectives

1
Create Path objects and inspect file-system metadata with exists(), is_file(), is_dir(), and stat()
2
Read file content with Path.read_text() and write content with Path.write_text()
3
Create nested directory trees with Path.mkdir(parents=True, exist_ok=True)
4
Open files for line-by-line reading and appending with Path.open()
5
List directory contents with Path.iterdir() and filter with Path.glob()
6
Rename files with Path.rename() and delete files with Path.unlink()
7
Combine pathlib primitives into a script that reads a deploy config and writes a timestamped run log
Step 1

Set up the lesson 201 workspace

Create a dedicated directory for this lesson and confirm the virtual environment is active. `pathlib` is part of the Python standard library — no pip install needed.

Commands to Run

mkdir -p ~/devops-python/lesson-201
cd ~/devops-python/lesson-201
source ~/devops-python/lesson-101/devops-env/bin/activate
python3 -c "from pathlib import Path; print('pathlib OK:', Path.cwd())"

What This Does

pathlib was added to the Python standard library in Python 3.4 and is the recommended way to work with file paths in modern Python.

It replaces the older os.path string-manipulation approach with an object-oriented API where a Path object represents a file or directory location and carries methods for reading, writing, and inspecting it.

Because it is part of the standard library, there is nothing to install.

Expected Outcome

Your terminal prompt shows (devops-env).

The one-liner prints pathlib OK: followed by the full path to your lesson-201 directory, for example pathlib OK: /Users/yourname/devops-python/lesson-201.

Pro Tips

  • 1
    If you placed your virtual environment at a different path in Lesson 101, adjust the `source` command to match your actual venv location.
  • 2
    You can always confirm which Python is active with `which python3` — it should point inside the `devops-env` directory.
Was this step helpful?

All Steps (0 / 8 completed)