Module 17 β OS & System Modules
Working with folders, paths, and files on disk from inside Python.
Prerequisite: Module 16 β File I/O
After this lesson, you will be able to
- Navigate and inspect the filesystem with os and pathlib
- Create, rename, and delete files and folders
- Copy and move files with shutil
Concept & Syntax
The os and pathlib modules let a Python program interact with the filesystem
itself β listing folders, building paths that work on Windows and Mac/Linux, and creating or removing
directories. shutil adds higher-level file operations like copying and moving.
pathlib is the modern, recommended approach: it represents a file path as an object (not just a
string), which makes path-building far less error-prone across operating systems.
from pathlib import Path
p = Path("data") / "scores.csv"
p.exists()
p.parent
os.listdir(".")Examples
Building a path with pathlib Very Easy
from pathlib import Path
data_file = Path("data") / "scores.csv"
print(data_file)The / operator joins path pieces correctly for the current operating system β no manual slash or backslash handling needed.
Checking existence and listing a folder Easy
import os
from pathlib import Path
print(Path("data").exists())
for name in os.listdir("."):
print(name)exists() checks whether a path is actually there; os.listdir(path) lists everything inside a folder.
Creating folders Intermediate
import os
os.makedirs("reports/2026", exist_ok=True)makedirs() creates every missing folder in the path; exist_ok=True stops it from raising an error if the folder is already there.
Copying and moving files Real World
import shutil
shutil.copy("notes.txt", "backup_notes.txt")
shutil.move("backup_notes.txt", "archive/backup_notes.txt")shutil.copy() duplicates a file; shutil.move() relocates it (and can also be used to rename).
Visual Explanation
π‘ Why does this work?
Read the concept explanation above again slowly, line by line β every keyword there maps directly onto a line of code in the examples. If it still doesn't click, re-run the traced example (if this lesson has one) one step at a time.
π What happens internally? (advanced)
Under the hood, Python compiles your source into bytecode and runs it on a virtual machine (the CPython interpreter). Variables are names in a namespace dictionary pointing at objects in memory β which is exactly what the memory panel in the tracer above is showing you.
Common Mistakes
Deleting a file or folder with os functions is permanent β there's no recycle bin/trash involved.
import os
os.remove("important_report.txt") # gone immediately, no confirmationimport os
if os.path.exists("important_report.txt"):
confirm = input("Really delete important_report.txt? (yes/no) ")
if confirm == "yes":
os.remove("important_report.txt")- Prefer pathlib.Path over manually building path strings with + or string formatting.
- Always check exists() before deleting or overwriting something irreversible.
- Use exist_ok=True with os.makedirs() to avoid errors when a folder might already be there.
Exercise & Challenge
Exercise 1 β Predict the output
from pathlib import Path
p = Path("images") / "cat.png"
print(p.suffix)What does this print?
π Challenge
Write a script that creates a folder called 'archive' if it doesn't exist, then lists every file in the current directory that ends with '.txt'.
- Use os.makedirs with exist_ok=True
- Use os.listdir() and check each name with .endswith('.txt')
- Print each matching filename
π‘ Need a hint?
"report.txt".endswith(".txt") is True.
π Show a sample solution
import os
os.makedirs("archive", exist_ok=True)
for name in os.listdir("."):
if name.endswith(".txt"):
print(name)Quiz
Answer every question, then submit to see your score and explanations.
1. What does the / operator do between two Path objects?
2. What does exist_ok=True do in os.makedirs()?
3. Which module provides high-level file operations like copy and move?
Summary
- pathlib.Path represents file paths as objects and handles OS differences automatically.
- os.listdir(), os.makedirs(), and os.remove() manage folders and files directly.
- shutil.copy() and shutil.move() handle higher-level file operations.
- Always double-check before deleting β filesystem operations are usually permanent.