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.
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
- makedirs creates parents.
- listdir order is arbitrary.
- rmtree deletes permanently.
Code examples
Creating and listing folders
['README.md', 'src'] ['main.py', 'utils']
Walking a tree
project ['README.md'] project/src ['main.py'] project/src/utils ['helpers.py']
More examples
Organising files by extension
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:
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
Prefer
mkdir creates only the last folder.
Deleting without checking
Avoid
Prefer
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
- 1Write a script that prints the total size of all files under a folder.
- 2Back 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?