The Python os module allows developers to interact directly with the operating system. Whether you want to manage files, create folders, read environment variables, or automate system tasks, the os module in Python is an essential tool for real-world programming.
In this tutorial, you’ll learn the Python os module from basics to advanced, with simple explanations and practical examples that you can use in real projects.
What Is the OS Module in Python?
The os module is a built-in Python library that provides functions to:
- Work with files and directories
- Handle file paths safely
- Access environment variables
- Run operating system commands
The biggest advantage of the Python os module is that it works across Windows, Linux, and macOS, making your code platform-independent.
How to Import the OS Module
The os module comes preinstalled with Python.
import os
Once imported, you can start interacting with the operating system.
Get the Current Working Directory
import os
print(os.getcwd())
Real-world use:
Useful when you want to know where your Python script is running, especially in automation and deployment scripts.
List Files and Directories in Python
os.listdir()
List files inside a specific folder:
os.listdir("Documents")
Use case:
File managers, backup scripts, and file-search tools.
Create and Delete Directories
Create a Directory
os.mkdir("my_folder")
Create multiple folders at once:
os.makedirs("projects/python/app")
Delete a Directory
os.rmdir("my_folder")
⚠️ The directory must be empty.
Real-world use:
Automatically creating project structures.
File Handling Using OS Module
Check If a File or Folder Exists
os.path.exists("data.txt")
Check File or Directory Type
os.path.isfile("data.txt")
os.path.isdir("Documents")
Rename a File or Folder
os.rename("old_name.txt", "new_name.txt")
Delete a File
os.remove("data.txt")
⚠️ Deleted files cannot be recovered.
Working with File Paths (Very Important)
Different operating systems use different path formats.
The os.path module solves this problem.
Join Paths Safely
os.path.join("folder", "file.txt")
✅ Best practice for cross-platform compatibility.
Get File Name and Directory Name
path = "/home/user/file.txt"
os.path.basename(path)
os.path.dirname(path)
Get File Extension
os.path.splitext("image.png")
Use case:
Filtering files by type (images, videos, PDFs).
Environment Variables Using OS Module
Environment variables store system-level or sensitive data.
Read Environment Variables
os.environ.get("HOME")
Windows example:
os.environ.get("USERNAME")
Set Environment Variables
os.environ["APP_MODE"] = "production"
Real-world use:
- API keys
- Database credentials
- App configuration
Running System Commands in Python
os.system("ls") # Linux / macOS
os.system("dir") # Windows
Use case:
Automation, system monitoring, DevOps scripts.
⚠️ For advanced control, use the subprocess module.
Walking Through Directories (Advanced)
for root, dirs, files in os.walk("projects"):
print(root)
print(files)
Real-world use:
- Backup tools
- File scanners
- Code analyzers
Real-World Python OS Module Examples
Delete All Temporary Files
import os
for file in os.listdir():
if file.endswith(".tmp"):
os.remove(file)
Create Daily Log Folder Automatically
import os
from datetime import date
folder = str(date.today())
if not os.path.exists(folder):
os.mkdir(folder)
Common Mistakes When Using OS Module
❌ Hard-coding file paths
❌ Not checking if a file exists
❌ Deleting files without validation
❌ Ignoring cross-platform compatibility
✅ Always use os.path.join() and os.path.exists().
Final Thoughts
The Python os module is one of the most important libraries for real-world Python development. From file handling to automation, it gives your programs the power to interact directly with the operating system.
If Python is the brain 🧠
Then the os module is the hands 👐