|
Getting your Trinity Audio player ready...
|
Have you ever wondered how Python interacts with your computer — like creating folders, reading files, checking what’s inside a directory, or deleting unwanted stuff?

That’s where the OS module comes in.
Think of it as Python’s bridge to your computer’s operating system. It lets your Python code talk directly to your file system — opening, moving, renaming, and organizing files, just like you do manually in File Explorer or Finder.
What is the OS Module in Python?
The os module in Python provides a way to use operating system-dependent functionality like file and directory operations, environment variables, and more.
It’s part of Python’s standard library, so you don’t need to install anything extra.
Just import it and start using it right away:
import os
Why Use the OS Module?
Here are some real-world situations where os is extremely useful:
- Automatically create folders for monthly reports.
- Rename or move files based on patterns.
- Delete unwanted logs or temp files automatically.
- Read environment variables like system paths or credentials.
- Build file management tools, data pipelines, and automation scripts.
Commonly Used OS Module Functions
Let’s explore the most important and frequently used functions in the OS module, along with examples.
1. Get Current Working Directory
import os
print(os.getcwd())
Output:
C:\Users\SmartTejas\Documents\Python
✅ Use this to know where your Python script is running.
2. Change Directory
os.chdir("C:/Users/SmartTejas/Desktop")
print("Directory changed:", os.getcwd())
✅ Switch between folders dynamically in your scripts.
3. List All Files and Folders
files = os.listdir()
print(files)
Output:
['project.py', 'data.csv', 'images', 'README.txt']
✅ Useful when scanning folders to process multiple files automatically.
4. Make a New Folder
os.mkdir("reports")
✅ Creates a new folder named reports in the current directory.
5. Make Nested Folders
os.makedirs("2025/reports/january", exist_ok=True)
✅ Creates multiple directories in one go (if they don’t exist).
6. Remove a Folder
os.rmdir("reports")
✅ Deletes a single folder (only if it’s empty).
If you need to delete nested folders, use shutil.rmtree() from the shutil module.
7. Rename a File or Folder
os.rename("oldname.txt", "newname.txt")
✅ Perfect for renaming downloaded files automatically.
8. Check if File or Directory Exists
if os.path.exists("data.csv"):
print("File exists!")
else:
print("File not found!")
✅ Prevents errors by verifying paths before accessing them.
9. Get File Size
size = os.path.getsize("data.csv")
print("File size:", size, "bytes")
✅ Useful to monitor large log files or ensure uploads aren’t empty.
10. Get Absolute Path
path = os.path.abspath("project.py")
print(path)
✅ Returns the full path to any file — great for file tracking or logging.
11. Split File Path and Name
path = "C:/Users/SmartTejas/Documents/report.xlsx"
print(os.path.basename(path))
print(os.path.dirname(path))
Output:
report.xlsx
C:/Users/SmartTejas/Documents
✅ Useful when handling files dynamically.
12. Join Paths Safely
Instead of manually adding slashes, use:
file_path = os.path.join("reports", "2025", "summary.txt")
print(file_path)
Output (on Windows):
reports\2025\summary.txt
✅ Ensures platform-independent paths (works on Windows, macOS, Linux).
13. Walk Through All Subdirectories
for root, dirs, files in os.walk("."):
print("Root:", root)
print("Directories:", dirs)
print("Files:", files)
✅ Perfect for exploring entire folder structures — like searching for files recursively.
Environment Variables with os
Environment variables store system-level values like paths, usernames, or keys.
Get Environment Variable
print(os.getenv('PATH'))
Set Environment Variable
os.environ['MY_ENV'] = 'Production'
print(os.getenv('MY_ENV'))
✅ Helpful for managing configuration securely.
Useful OS Constants
| Constant | Description |
|---|---|
os.name | Returns the OS name (posix, nt, etc.) |
os.sep | Path separator (/ or \) |
os.pathsep | Used to separate paths (; or :) |
os.linesep | Newline character (\n or \r\n) |
Example:
print(os.name)
print(os.sep)
Real-Life Use Cases
| Scenario | Example |
|---|---|
| Clean up old log files | Use os.remove() to delete old logs automatically |
| Organize downloads | Move images, videos, and docs into separate folders |
| Manage configuration | Use environment variables for credentials |
| Automate backups | Create timestamped folders using os.makedirs() |
Mini Project: File Organizer in Python
Let’s use everything we learned to build something practical —
a File Organizer Tool that automatically arranges files into folders based on their type.
Project Goal
You’ll build a Python script that scans a directory (like your Downloads folder) and moves files into separate folders such as:
📁 Downloads
├── Images
├── Documents
├── Videos
├── Others
Step-by-Step Implementation
1. Import Modules
We’ll use both os and shutil modules.
import os
import shutil
2. Define the Target Directory
source_dir = r"C:\Users\SmartTejas\Downloads"
Change this path as per your system.
3. Create Folder Categories
We’ll define which file types go where.
folders = {
'Images': ['.jpg', '.jpeg', '.png', '.gif'],
'Documents': ['.pdf', '.docx', '.txt', '.xlsx'],
'Videos': ['.mp4', '.mov', '.avi'],
'Music': ['.mp3', '.wav'],
'Archives': ['.zip', '.rar'],
}
4. Create Folders if They Don’t Exist
for folder in folders.keys():
folder_path = os.path.join(source_dir, folder)
if not os.path.exists(folder_path):
os.makedirs(folder_path, exist_ok=True)
5. Scan and Move Files
for filename in os.listdir(source_dir):
file_path = os.path.join(source_dir, filename)
if os.path.isfile(file_path):
_, ext = os.path.splitext(filename)
moved = False
for folder_name, extensions in folders.items():
if ext.lower() in extensions:
shutil.move(file_path, os.path.join(source_dir, folder_name, filename))
print(f"Moved: {filename} → {folder_name}")
moved = True
break
if not moved:
other_path = os.path.join(source_dir, 'Others')
if not os.path.exists(other_path):
os.makedirs(other_path, exist_ok=True)
shutil.move(file_path, os.path.join(other_path, filename))
print(f"Moved: {filename} → Others")
Sample Output
Moved: report.pdf → Documents
Moved: photo.jpg → Images
Moved: movie.mp4 → Videos
Moved: song.mp3 → Music
Moved: random_file.xyz → Others
Code Explanation
Step 1: Import Required Modules
We import os to interact with the file system and shutil to move files easily.
import os
import shutil
Step 2: Define the Working Directory
This tells Python which folder to organize.
source_dir = r"C:\Users\SmartTejas\Downloads"
You can replace it with any folder you want.
Step 3: Define File Categories
Here, we group file types under different folders.
folders = {
'Images': ['.jpg', '.jpeg', '.png'],
'Documents': ['.pdf', '.docx', '.txt'],
}
Python will check each file’s extension and decide where to move it.
Step 4: Create Missing Folders
If a category folder doesn’t exist, this step will create it automatically.
os.makedirs(folder_path, exist_ok=True)
This avoids errors if folders are missing.
Step 5: Scan and Move Files
We loop through each file, check its extension, and move it to the correct folder using:
shutil.move(source, destination)
If a file doesn’t match any category, it’s moved to an “Others” folder.
Error Handling (Optional Improvement)
Let’s make it safer with try...except.
try:
shutil.move(file_path, destination)
except Exception as e:
print(f"Error moving {filename}: {e}")
Read More: Error Handling in Python
OS Module Cheat Sheet
| Function Name | Usage / Description | Example |
|---|---|---|
os.getcwd() | Returns the current working directory | os.getcwd() → 'C:\\Users\\Admin\\Documents' |
os.chdir(path) | Changes the current working directory | os.chdir("C:/Users/Admin/Desktop") |
os.listdir(path) | Lists all files and folders in the directory | os.listdir("C:/Users/Admin") |
os.mkdir(path) | Creates a new directory (single level) | os.mkdir("reports") |
os.makedirs(path) | Creates nested directories | os.makedirs("2025/reports/january") |
os.rmdir(path) | Removes an empty directory | os.rmdir("reports") |
os.remove(path) | Deletes a file | os.remove("old_data.csv") |
os.rename(src, dst) | Renames or moves a file/folder | os.rename("old.txt", "new.txt") |
os.path.exists(path) | Checks if a file or folder exists | os.path.exists("data.csv") |
os.path.isfile(path) | Checks if the path is a file | os.path.isfile("data.csv") |
os.path.isdir(path) | Checks if the path is a directory | os.path.isdir("reports") |
os.path.getsize(path) | Returns file size in bytes | os.path.getsize("report.pdf") |
os.path.abspath(path) | Returns the absolute (full) path | os.path.abspath("main.py") |
os.path.basename(path) | Returns the file name from a path | os.path.basename("C:/files/report.pdf") |
os.path.dirname(path) | Returns the directory part of a path | os.path.dirname("C:/files/report.pdf") |
os.path.join(a, b) | Joins paths safely (cross-platform) | os.path.join("folder", "file.txt") |
os.walk(path) | Iterates through directories & subdirectories | for root, dirs, files in os.walk("."): |
os.getenv(key) | Returns the value of an environment variable | os.getenv("PATH") |
os.environ[key] = value | Sets an environment variable | os.environ["MODE"] = "Production" |
os.name | Returns the OS type (nt, posix) | os.name → 'nt' |
os.sep | Path separator used by the OS | '\\' on Windows, '/' on Linux |
os.linesep | Newline character used by the OS | '\r\n' on Windows |
os.pathsep | Separator for file paths in environment variables | ';' on Windows |
Shutil Module Cheat Sheet
| Function Name | Usage / Description | Example |
|---|---|---|
shutil.copy(src, dst) | Copies a file to a new location (keeps metadata) | shutil.copy("data.csv", "backup/") |
shutil.copy2(src, dst) | Same as copy() but preserves metadata like creation/modification time | shutil.copy2("report.pdf", "archive/") |
shutil.move(src, dst) | Moves a file or folder to a new location | shutil.move("old/file.txt", "new_folder/") |
shutil.rmtree(path) | Deletes a directory and all its contents recursively | shutil.rmtree("temp_files") |
shutil.make_archive(base_name, format, root_dir) | Creates a ZIP or TAR archive of a folder | shutil.make_archive("backup", "zip", "project_folder") |
shutil.unpack_archive(filename, extract_dir) | Extracts a ZIP/TAR archive to a directory | shutil.unpack_archive("backup.zip", "restore_folder") |
shutil.disk_usage(path) | Returns total, used, and free disk space | shutil.disk_usage("/") |
shutil.which(cmd) | Returns the path of a command (like "python") | shutil.which("python") |
Note: To use shutil module, use: import shutil in your project
Final Thoughts
With the OS module, you can automate:
- Cleaning messy folders
- Sorting downloaded files
- Managing log or report archives
- Backing up data automatically
This small project is just the beginning. Combine os, datetime, and shutil, and you can build powerful file automation tools for your daily workflows.
Conclusion
The OS module in Python gives you complete control over your file system — whether you’re managing directories, renaming files, or building automation projects.
With the File Organizer Project, you’ve seen how to put this into real action.
Next time your downloads folder looks like chaos, just run your Python script and let automation handle it.
What’s Next?
In the next post, we’ll learn about the Pathlib Module in Python