OS Module
Learn how to interact with the operating system in Python using the os module, including directories, paths, and environment variables.
Introduction
Many real programs need to interact with the file system and the operating system itself — finding out which folder they are running in, listing files, creating directories, or reading configuration values set outside the program. Python's built-in os module provides all of these capabilities.
This lesson tours the most commonly used parts of the os module: working directories, listing and creating folders, checking paths, and reading environment variables — plus a look at pathlib, the more modern alternative for path handling.
- How to get and change the current working directory.
- How to list the contents of a directory.
- How to create and remove directories.
- How to check whether a path exists, and whether it is a file or a directory.
- How to read environment variables with os.environ.
- Why pathlib is often preferred over os.path in modern Python code.
The os Module
The os module is part of Python's standard library and provides a way to interact with the operating system — regardless of whether you are running on Windows, macOS, or Linux.
import os
print(os.name)ntos.name reports "nt" on Windows and "posix" on macOS/Linux. Most os functions work consistently across platforms despite these underlying differences.
Current Working Directory
The current working directory is the folder your script is considered to be "running from." os.getcwd() returns it, and os.chdir() changes it.
import os
print(os.getcwd())
os.chdir("..")
print(os.getcwd())D:\Projects\python_course
D:\Projectsos.chdir() changes the working directory for the rest of the running program, not just one function. Changing it unexpectedly can break relative file paths used elsewhere in your code.
Listing Directory Contents
os.listdir(path) returns a list of the names of files and folders inside the given directory. If no path is given, it lists the current working directory.
import os
items = os.listdir(".")
print(items)['data.csv', 'main.py', 'notes.txt', 'scripts']Note that os.listdir() returns both files and subdirectories mixed together, without distinguishing between them — you need os.path to tell them apart, which we'll cover shortly.
Creating and Removing Directories
os.mkdir(path) creates a new directory. os.rmdir(path) removes an existing, empty directory. Both raise an error under certain conditions — mkdir() fails if the folder already exists, and rmdir() fails if the folder is not empty.
import os
os.mkdir("reports")
print("reports" in os.listdir("."))
os.rmdir("reports")
print("reports" in os.listdir("."))True
FalseTo create nested folders in one call (e.g. "a/b/c"), use os.makedirs() instead, which creates any missing parent directories along the way.
import os
os.makedirs("projects/2026/reports", exist_ok=True)
print(os.path.exists("projects/2026/reports"))TrueChecking Paths with os.path
The os.path submodule provides functions for building and inspecting file paths in a way that works correctly on any operating system.
os.path.exists(path)
Returns True if the given file or folder exists.
os.path.join(a, b)
Joins path segments using the correct separator for the current OS.
os.path.isfile(path)
Returns True only if the path points to a file.
os.path.isdir(path)
Returns True only if the path points to a directory.
import os
folder = "data"
filename = "report.csv"
full_path = os.path.join(folder, filename)
print(full_path)
print(os.path.exists(full_path))
print(os.path.isfile(full_path))
print(os.path.isdir(folder))data\report.csv
True
True
TrueBuilding paths manually with "folder" + "/" + "file" breaks on Windows, which uses backslashes. os.path.join() always uses the correct separator for whichever operating system the code runs on.
Environment Variables
Environment variables are values set outside your program, often used for configuration like API keys, file paths, or system settings. os.environ gives you access to them as a dictionary-like object.
import os
# Read an existing environment variable, with a fallback default
username = os.environ.get("USERNAME", "unknown")
print("Current user:", username)
# Set a new environment variable for this program's session
os.environ["APP_MODE"] = "development"
print(os.environ.get("APP_MODE"))Current user: student
developmentUsing .get() with a default value is safer than os.environ["KEY"] directly, since accessing a missing key with square brackets raises a KeyError.
pathlib: A Modern Alternative
While os.path works well, modern Python code often prefers the pathlib module, which represents paths as objects instead of plain strings, making path code more readable and less error-prone.
from pathlib import Path
folder = Path("data")
file_path = folder / "report.csv" # paths can be joined with /
print(file_path)
print(file_path.exists())
print(file_path.suffix)data\report.csv
True
.csvos.path
The traditional, function-based approach — works with plain strings.
pathlib
The modern, object-oriented approach — paths are objects with useful methods like .exists() and .suffix.
Common Mistakes
- Building paths manually with string concatenation instead of os.path.join() or pathlib.
- Calling os.rmdir() on a non-empty directory, which raises an OSError.
- Using os.environ["KEY"] without checking existence first, risking a KeyError.
- Forgetting that os.chdir() changes the directory for the entire program, not just the current function.
- Assuming os.listdir() distinguishes files from folders — it does not, you must check separately with os.path.
Best Practices
- Prefer os.path.join() or pathlib over manual string concatenation for paths.
- Use os.makedirs(path, exist_ok=True) to safely create nested folders without errors.
- Use os.environ.get("KEY", default) to safely read environment variables.
- Check os.path.exists() before reading or writing to a path when uncertain.
- Consider pathlib for new code, since it is more readable and included in the standard library.
Frequently Asked Questions
What is the difference between os.mkdir() and os.makedirs()?
os.mkdir() creates a single directory and fails if any parent folder in the path is missing. os.makedirs() creates all necessary parent directories along the way.
Why should I use os.path.join() instead of string concatenation?
os.path.join() automatically uses the correct path separator for the current operating system (backslash on Windows, forward slash on macOS/Linux), preventing broken paths.
How do I check if something is a file versus a folder?
Use os.path.isfile(path) to check for a file, and os.path.isdir(path) to check for a directory. Both return False if the path does not exist at all.
Is pathlib meant to replace os.path completely?
Not entirely — os.path still works fine and is used throughout many existing codebases, but pathlib is generally recommended for new code because of its more readable, object-oriented interface.
How do I safely read an environment variable that might not exist?
Use os.environ.get("KEY", "default_value") instead of os.environ["KEY"], so your program returns a fallback instead of crashing with a KeyError.
Key Takeaways
- os.getcwd() and os.chdir() get and change the working directory.
- os.listdir() lists the contents of a folder.
- os.mkdir()/os.makedirs() create directories, and os.rmdir() removes empty ones.
- os.path.exists(), os.path.join(), os.path.isfile(), and os.path.isdir() help you work safely with paths.
- os.environ gives access to environment variables, and pathlib offers a more modern, object-oriented alternative to os.path.
Summary
The os module gives Python programs a consistent way to interact with the file system and operating system across Windows, macOS, and Linux — from navigating folders to reading environment configuration.
In this lesson, you learned how to work with the current directory, list and manage folders, check paths safely, read environment variables, and how pathlib offers a modern alternative to os.path.
- You can navigate and inspect the file system using the os module.
- You can safely build and check file paths.
- You can read environment variables from your program.
- You are ready to explore JSON handling in Python.