Skip to content

Module 13 · File Handling — topic 13 of 15

Directories

Working with folders: creating directories with os.makedirs, listing contents, walking a directory tree with os.walk, moving and deleting files and folders with shutil, and organising files automatically.

Beginner 10 min read·Lesson 206 of 306 in Python Programming

Learning objectives

  • Create and list directories
  • Walk through a directory tree
  • Move, copy and delete files and folders

Definition

A directory (folder) contains files and other directories. The os and shutil modules create, list, move, copy and delete directories and their contents.

Introduction

Organising downloads, backing up a project folder, cleaning old logs — automating folder work is one of the most practical uses of Python.

Why it matters

Directory operations let scripts manage whole collections of files rather than one at a time.

Detailed explanation

os.mkdir(path) creates one directory; os.makedirs(path, exist_ok=True) creates all missing parents and doesn't fail if it already exists.

os.listdir(path) returns the names in a directory in arbitrary order — sort them when order matters.

os.walk(top) yields (folder, subfolders, files) for every folder in the tree; sorting the subfolders list in place controls the order of traversal.

shutil.copy(src, dst) copies a file; shutil.copytree copies a folder; shutil.move moves or renames.

os.remove deletes a file, os.rmdir deletes an empty folder, and shutil.rmtree deletes a folder and everything in it — permanently, without a recycle bin.

os.rename and os.replace rename files; os.replace overwrites the destination if it exists.

Destructive operations deserve care: print what would happen first (a 'dry run') before deleting or moving many files.

When you change a folder while looping over it, take the listing first (as a sorted list) and then act on it. Modifying a folder while iterating over a live listing can skip files or process new ones twice.

Syntax

Python
import os, shutil
os.makedirs("backup/2026", exist_ok=True)
for name in sorted(os.listdir(".")):
print(name)
shutil.copy("notes.txt", "backup/2026/notes.txt")
  • makedirs creates parents.
  • listdir order is arbitrary.
  • rmtree deletes permanently.

Code examples

Creating and listing folders

Python
import os
os.makedirs("project/src/utils", exist_ok=True)
for name in ["project/README.md", "project/src/main.py", "project/src/utils/helpers.py"]:
with open(name, "w", encoding="utf-8") as f:
f.write("# file\n")
print(sorted(os.listdir("project")))
print(sorted(os.listdir("project/src")))
Output
['README.md', 'src']
['main.py', 'utils']

Walking a tree

Python
import os
os.makedirs("project/src/utils", exist_ok=True)
for name in ["project/README.md", "project/src/main.py", "project/src/utils/helpers.py"]:
open(name, "w", encoding="utf-8").close()
for root, dirs, files in os.walk("project"):
dirs.sort()
print(root.replace(os.sep, "/"), sorted(files))
Output
project ['README.md']
project/src ['main.py']
project/src/utils ['helpers.py']

More examples

Organising files by extension

Python
import os
import shutil
os.makedirs("downloads", exist_ok=True)
for name in ["photo.jpg", "notes.txt", "song.mp3", "scan.jpg", "todo.txt"]:
open(os.path.join("downloads", name), "w", encoding="utf-8").close()
for name in sorted(os.listdir("downloads")):
path = os.path.join("downloads", name)
if os.path.isfile(path):
ext = os.path.splitext(name)[1][1:] or "other"
os.makedirs(os.path.join("downloads", ext), exist_ok=True)
shutil.move(path, os.path.join("downloads", ext, name))
for folder in sorted(os.listdir("downloads")):
print(folder, sorted(os.listdir(os.path.join("downloads", folder))))
shutil.rmtree("downloads")
print(os.path.exists("downloads"))
Output
jpg ['photo.jpg', 'scan.jpg']
mp3 ['song.mp3']
txt ['notes.txt', 'todo.txt']
False

Step-by-step explanation

  • The listing is taken once before moving, so new folders don't interfere.
  • Each file goes into a folder named after its extension, created on demand.
  • rmtree removes the example folder at the end — in real use, double-check the path before deleting.

Expected output

Running “Organising files by extension” prints exactly:

TextOutput
jpg ['photo.jpg', 'scan.jpg']
mp3 ['song.mp3']
txt ['notes.txt', 'todo.txt']
False

Practical applications

  • Download-folder organisers and photo sorters.
  • Backup and cleanup scripts.

Best practices

  • Use makedirs with exist_ok=True.
  • Sort listings for predictable order.
  • Dry-run destructive operations first.

Common mistakes

os.mkdir for nested folders

Avoid

os.mkdir("a/b/c") # fails if a/b doesn't exist

Prefer

os.makedirs("a/b/c", exist_ok=True)

mkdir creates only the last folder.

Deleting without checking

Avoid

shutil.rmtree(user_input)

Prefer

Validate the path and confirm before deleting.

rmtree on the wrong folder destroys data permanently.

Important notes

  • pathlib offers the same operations as methods: Path.mkdir, Path.iterdir, Path.rglob.

Key takeaways

  • makedirs creates nested folders.
  • listdir and walk explore folders.
  • shutil copies, moves and deletes trees.

Try it yourself

  1. 1
    Write a script that prints the total size of all files under a folder.
  2. 2
    Back up all .txt files from one folder into a dated backup folder.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

8 questions cover the “File Handling” module. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
  • ModerateWhat is printed?
  • ModerateWhich mode creates a new file but fails if the file already exists?
Practise this module