Working with files and folders is one of the first real-world tasks you’ll do in Python. This page walks you through Python os module basics for files and folders: creating directories, listing files, joining paths, walking through directories, renaming/moving, and deleting safely. If you’re just starting your Python journey, this beginner guide to the Python os module for file handling uses simple, cross‑platform examples you can run right away. For more Python tutorials, visit the CodDesire Python hub.
- Use
osfor create/list/rename/remove;os.pathorpathlibfor paths;shutilfor copy/move/rmtree. - Build portable paths with
os.path.joinorPath(...)/"child"instead of hard‑coding slashes. - Prefer
os.replace()overos.rename()when you may need to overwrite across platforms. - Delete with care: file →
os.remove, empty dir →os.rmdir, whole tree →shutil.rmtree. - Write safe code with
try/exceptforFileNotFoundError/PermissionErrorand useexist_ok=Truefor idempotent directory creation.
What is the Python os module and why is it used?
The os module gives Python programs a cross‑platform way to talk to your operating system. For files and folders, it provides the low‑level building blocks to:
- Create directories (
os.mkdir,os.makedirs) - List and traverse directories (
os.listdir,os.scandir,os.walk) - Rename or move entries (
os.rename,os.replace) - Remove files and folders (
os.remove/os.unlink,os.rmdir) - Work with paths (
os.path) and metadata (os.stat)
Modern best practice is to use os for these concrete operations, os.path or pathlib for building and inspecting paths, and shutil for higher‑level actions like copying or removing whole directory trees.
| Task | Use this | Notes |
|---|---|---|
| Create a single directory | os.mkdir(path) |
Fails if parent missing or already exists |
| Create nested directories | os.makedirs(path, exist_ok=True) |
Idempotent with exist_ok=True |
| List names in a folder | os.listdir(path) |
Returns names only; join to get full paths |
| List with type checks (files/dirs) | os.scandir(path) |
Faster; use entry.is_file(), entry.is_dir() |
| Walk a directory tree | os.walk(path) |
Modify dirs[:] to skip folders |
| Build portable paths | os.path.join(...) or Path(...)/"child" |
Avoid hard‑coding / or |
| Get absolute path | os.path.abspath(path) |
Helpful before destructive actions |
| Rename/move on same drive | os.rename or os.replace |
os.replace overwrites portably |
| Move across drives/partitions | shutil.move |
Falls back to copy‑then‑delete |
| Delete a file | os.remove / os.unlink |
Catch FileNotFoundError |
| Delete an empty directory | os.rmdir |
Fails if not empty |
| Delete a folder tree | shutil.rmtree |
Destructive — double‑check the path |
| Inspect size/timestamps | os.stat |
Use with datetime.fromtimestamp |
Getting started: current directory and basic setup
Before creating or listing files, it helps to know your current working directory (where your script is running from).
# Where are we?
print("CWD:", os.getcwd())
# Change directory (optional; be careful in larger apps)
# os.chdir("path/to/some/folder")
CWD: /home/student/projectsHow to create and remove directories in Python with os
Creating folders is a common first step in a script—e.g., making a data or output directory. Here’s how:
Create a single folder
os.mkdir("data") # creates ./data (must not already exist)
print("Created 'data'")
Create nested folders safely
Use os.makedirs to create parent directories automatically. With exist_ok=True, it won’t raise an error if the path already exists.
os.makedirs("data/raw/images", exist_ok=True)
print("Ensured 'data/raw/images' exists")
Remove an empty directory
Note: os.rmdir() removes only empty directories. To remove a folder with files inside, use shutil.rmtree() (shown later).
os.rmdir("data") # works only if 'data' is empty
How do I list all files in a folder using Python os?
There are two primary ways: os.listdir() and os.scandir().
os.listdir: get names in a directory
os.listdir(path) returns a list of names (strings). It does not include full paths unless you join them yourself.
for name in os.listdir("."):
print(name)
main.py
notes.txt
data
imagesos.scandir: efficient iteration with file type checks
os.scandir() yields DirEntry objects with .is_file() and .is_dir() methods that are often faster because they can avoid extra system calls. This is useful for “python list files in directory” tasks that need filtering.
with os.scandir(".") as entries:
for entry in entries:
if entry.is_file():
print("FILE:", entry.name)
elif entry.is_dir():
print("DIR :", entry.name)
Python os path basics: building and inspecting paths
Never hard‑code path separators like / or . Use os.path to write portable code.
# Join parts safely (Windows, macOS, Linux)
p = os.path.join("data", "raw", "report.csv")
print(p)
# Get absolute path
abs_p = os.path.abspath(p)
print(abs_p)
# Check existence and type
print(os.path.exists(p))
print(os.path.isfile(p))
print(os.path.isdir("data"))
# Break down paths
print(os.path.basename(p)) # 'report.csv'
print(os.path.dirname(p)) # 'data/raw'
print(os.path.splitext(p)) # ('data/raw/report', '.csv')
Joining and getting absolute paths with os.path
If you need to combine the safety of path objects with the power of os functions, pathlib works well too. Most os and shutil functions accept path‑like objects in modern Python.
import os
base = Path("data") / "raw"
file_path = base / "report.csv"
print(file_path) # data/raw/report.csv
print(file_path.exists()) # True/False
# You can still pass a Path to os.remove (path-like support)
if file_path.exists():
os.remove(file_path)
os.path vs pathlib (quick comparison)
| Feature | os.path | pathlib.Path |
|---|---|---|
| Style | String functions | Object-oriented paths |
| Joining | os.path.join(a, b) | Path(a) / b |
| Checks | exists, isfile, isdir | exists(), is_file(), is_dir() |
| Works with os/shutil | Yes | Yes (path-like protocol) |
Walking a directory tree with os.walk
Use os.walk() to visit every subfolder and file. You’ll often see this used for searching, counting, or bulk operations.
for root, dirs, files in os.walk("project"):
# Example: skip __pycache__ directories
dirs[:] = [d for d in dirs if d != "__pycache__"]
for name in files:
if name.endswith(".py"):
full_path = os.path.join(root, name)
print(full_path)
Rename or move files and folders
Use os.rename(src, dst) to rename or move within the same filesystem. Be aware of overwrite behavior differences across operating systems. If you want to overwrite if the destination exists, prefer os.replace(src, dst) for portability.
class="cd-package">import os
# Simple rename(may fail if 'new.txt' exists depending on OS)
os.rename("old.txt", "new.txt")
# Overwrite if needed(more portable)
os.replace("temp.txt", "final.txt")If you need to move across different disks or partitions, use shutil.move() instead. It can fall back to copy‑then‑delete if needed.
shutil.move("images/logo.png", "assets/logo.png")
Python delete file safely
Deleting requires care. You can check existence or use try/except to handle “file not found” cases gracefully.
Delete a file with a safety check
class="cd-package">import os
path = "output/results.txt"
if os.path.isfile(path):
os.remove(path)
print("Deleted:", path)
else:
print("No file to delete at:", path)Delete a file using try/except
This pattern avoids a small timing window between the check and delete on busy systems.
try:
os.remove("output/results.txt")
print("Deleted")
except FileNotFoundError:
print("Already gone")
Remove empty vs non-empty directories
os.rmdir() only removes empty directories. To remove a folder and everything in it, use shutil.rmtree().
import shutil
# Empty only
os.rmdir("temp/empty_folder")
# Recursive removal (careful!)
shutil.rmtree("temp/build")
File and folder metadata with os.stat
os.stat() returns size and timestamps; handy for quick checks.
from datetime import datetime
info = os.stat("notes.txt")
print("Size:", info.st_size, "bytes")
print("Modified:", datetime.fromtimestamp(info.st_mtime))
Quick recipes: Python os module examples for listing files and folders
1) List only .txt files in a directory
txt_files = [name for name in os.listdir(".") if name.endswith(".txt")]
print(txt_files)
2) Check if a file or directory exists in Python using os
print(os.path.exists("README.md"))
print(os.path.isdir("data"))
print(os.path.isfile("main.py"))
3) Create multiple nested folders if missing
os.makedirs(os.path.join("reports", "2026", "Q3"), exist_ok=True)
4) Join and get absolute paths in Python with os.path
p = os.path.join("images", "icons", "edit.png")
print("Rel:", p)
print("Abs:", os.path.abspath(p))
5) Walk a tree and count Python files
count = 0
for root, _, files in os.walk("."):
count += sum(1 for f in files if f.endswith(".py"))
print("Python files:", count)
6) Rename with overwrite using os.replace
class="cd-package">import os
src = "draft.txt"
dst = "final.txt"
os.replace(src, dst)- Work in a test/sandbox folder first; print your CWD with
os.getcwd(). - Build paths with
os.path.joinorPath; avoid hard‑coded separators. - Use absolute paths (
os.path.abspath) before any destructive action. - Create directories idempotently:
os.makedirs(..., exist_ok=True). - List efficiently and filter types:
os.scandir()withentry.is_file()/entry.is_dir(). - When walking trees, prune with
dirs[:]to skip folders like__pycache__. - Rename/move safely across OSes: prefer
os.replace(overwrite) orshutil.movefor cross‑device moves. - Delete carefully: file →
os.remove, empty dir →os.rmdir, tree →shutil.rmtree(double‑check the path!). - Handle errors: wrap deletes in
try/except FileNotFoundErrorand watch forPermissionError. - Verify results: check with
exists/isfile/isdirorPathmethods.
Common mistakes (and easy fixes)
- Using hard-coded slashes in paths. Fix: use
os.path.joinorpathlib.Path. - Expecting
os.rmdir()to remove non‑empty folders. Fix: useshutil.rmtree()for recursive deletion. - Forgetting that
os.listdir()returns names, not full paths. Fix: join withos.path.join(root, name). - Assuming
os.rename()always overwrites. Fix: useos.replace()for cross‑platform overwrite behavior. - Creating nested directories with
os.mkdir(). Fix: useos.makedirs(..., exist_ok=True). - Deleting without handling “not found.” Fix: wrap
os.remove()intry/except FileNotFoundError.
FAQ: People also ask
What is the Python os module and why is it used?
The os module provides a cross‑platform interface to your operating system. For files and folders, it lets you create directories, list and traverse folders, rename/move entries, remove files, and inspect metadata in a simple, portable way.
How do I list all files in a folder using Python os?
Use os.listdir(path) for a quick list of names, or os.scandir(path) to iterate efficiently and filter using entry.is_file() and entry.is_dir().
How can I create or delete a directory with Python os?
Create a single folder with os.mkdir("name"), or nested folders with os.makedirs("a/b/c", exist_ok=True). Delete an empty directory with os.rmdir("name"); for non‑empty directories, use shutil.rmtree("name").
What is the difference between os.path and pathlib in Python?
os.path is a set of string-based functions for path operations, while pathlib offers object-oriented paths (Path) with methods like exists() and the / operator for joining. Both are fully supported; use whichever feels clearer for your project.
How do I check if a file exists before deleting it in Python?
You can check with os.path.isfile(path), or safely try to delete and catch FileNotFoundError:
try:
os.remove("file.txt")
except FileNotFoundError:
pass
Why this approach is beginner-friendly and future-proof
The examples above stick to built-in modules and cross‑platform patterns. Python’s os, os.path, and shutil APIs have remained stable and are widely used in schools, colleges, and production code. When you’re ready, explore pathlib for cleaner path handling—most os/shutil functions accept path-like objects out of the box.
Keep practicing: build a small script to organize downloads, rename images, or archive reports. As you combine these small building blocks, you’ll quickly master how to use the os module in Python for everyday automation.
Continue learning on the CodDesire Python tutorials page.


