PyComplete Python Course
Intermediate 35 min

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.

Syntax
from pathlib import Path
p = Path("data") / "scores.csv"
p.exists()
p.parent
os.listdir(".")

Examples

Building a path with pathlib Very Easy

Building a path with pathlib
from pathlib import Path
data_file = Path("data") / "scores.csv"
print(data_file)
Outputdata/scores.csv

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

Checking existence and listing a folder
import os
from pathlib import Path
print(Path("data").exists())
for name in os.listdir("."):
    print(name)
OutputTrue (the files/folders in the current directory)

exists() checks whether a path is actually there; os.listdir(path) lists everything inside a folder.

Creating folders Intermediate

Creating folders
import os
os.makedirs("reports/2026", exist_ok=True)
Output(creates reports/2026, including reports if needed β€” no error if it already exists)

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

Copying and moving files
import shutil
shutil.copy("notes.txt", "backup_notes.txt")
shutil.move("backup_notes.txt", "archive/backup_notes.txt")
Output(copies then moves the file β€” no console output)

shutil.copy() duplicates a file; shutil.move() relocates it (and can also be used to rename).

Visual Explanation

Path("data") / "file.csv"os.path / pathlib resolves the correct path for this OSos / shutil performs the operation (create, copy, move, delete)Filesystem is updated
pathlib and os translate your intent into the right filesystem calls for the current OS.
πŸ’‘ 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

βœ— Common mistake 1

Deleting a file or folder with os functions is permanent β€” there's no recycle bin/trash involved.

βœ— Avoid this
This raises not a crash, but data loss if this was a mistake
import os
os.remove("important_report.txt")  # gone immediately, no confirmation
βœ“ Better approach
Fixed
import 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")
βœ“ Best practices
  • 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

Given this code
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
Python
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?

Divides numbers
Joins path segments correctly for the current OS
Deletes a file
Nothing, it's invalid
pathlib overloads / specifically for building file paths.

2. What does exist_ok=True do in os.makedirs()?

Deletes the folder if it exists
Prevents an error if the folder already exists
Makes the folder read-only
Has no effect
Without it, makedirs() raises an error if the target already exists.

3. Which module provides high-level file operations like copy and move?

os
sys
shutil
pathlib
shutil (shell utilities) provides copy(), move(), and similar high-level operations.

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.

Related lessons

Saved privately in your browser β€” no account needed.