Python OS Module Tutorial | File System Operations, Directories & Path Management
Modern Python applications frequently interact with the operating system to create files, organize directories, automate repetitive tasks, manage environment variables, and execute system-level operations. Whether you’re developing backend applications, automation scripts, DevOps tools, AI workflows, or desktop software, understanding the OS Module is essential.
Python’s built-in os and os.path modules provide a platform-independent way to work with files and directories. These modules allow developers to navigate the file system, create and delete folders, rename files, retrieve environment information, and build automation scripts that work across Windows, Linux, and macOS.
In this lesson, you’ll learn how to use the os module effectively, manage files and folders, work with paths, handle environment variables, and automate common system tasks using practical examples.
By the end of this lesson, you’ll be able to build Python applications that interact safely and efficiently with the operating system.
Learning Objectives
After completing this lesson, you will be able to:
- Understand the Python
osmodule. - Navigate the file system.
- Create, rename, and delete directories.
- Work with file paths using
os.path. - Retrieve environment variables.
- Automate file management tasks.
- Build platform-independent applications.
- Apply OS module concepts in real-world projects.
Topics Covered
- Introduction to the OS Module
- Working Directory
- Creating Directories
- Removing Directories
- Renaming Files & Folders
- Listing Directory Contents
- os.path Module
- Environment Variables
- Real-World Applications
- Best Practices
Detailed Lesson Content
Introduction to the OS Module
Imagine you’re developing an AI Document Processing System.
Every day the application:
- Reads uploaded files
- Creates project folders
- Stores reports
- Deletes temporary files
- Organizes datasets
Doing this manually would be impossible.
Python’s os module automates these tasks.
Importing the OS Module
import os
The os module provides functions for interacting with the operating system.
Getting the Current Working Directory
Example
import os
print(os.getcwd())
Output
C:\Users\Student\Projects
getcwd() returns the current directory where the Python program is running.
Changing the Working Directory
import os
os.chdir("D:\\PythonProjects")
print(os.getcwd())
This changes the current working directory.
Listing Files and Folders
import os
print(os.listdir())
Output
['main.py', 'students.json', 'images', 'reports']
To list a specific directory:
print(os.listdir("D:\\Projects"))
Creating a Directory
Create a single folder:
import os
os.mkdir("Assignments")
Output
Assignments folder created.
Creating Multiple Directories
import os
os.makedirs("Projects/Python/Beginner")
makedirs() creates nested folders automatically.
Renaming a File or Folder
import os
os.rename("Assignments", "PythonAssignments")
The folder name changes from Assignments to PythonAssignments.
Removing a Directory
Remove an empty folder:
import os
os.rmdir("PythonAssignments")
Removing Multiple Directories
import os
os.removedirs("Projects/Python/Beginner")
This removes nested empty directories.
Deleting a File
import os
os.remove("students.txt")
Always verify that the file exists before deleting it.
Checking if a File Exists
import os
if os.path.exists("students.txt"):
print("File Exists")
else:
print("File Not Found")
Output
File Exists
Working with os.path
The os.path module provides utilities for handling file paths.
Example
import os
path = "students.txt"
print(os.path.exists(path))
Getting Absolute Path
import os
print(os.path.abspath("students.txt"))
Output
C:\Users\Student\Projects\students.txt
Checking File or Directory
import os
print(os.path.isfile("students.txt"))
print(os.path.isdir("Projects"))
Output
True
True
Getting File Name
import os
path = "D:\\Projects\\report.pdf"
print(os.path.basename(path))
Output
report.pdf
Getting Folder Name
import os
path = "D:\\Projects\\report.pdf"
print(os.path.dirname(path))
Output
D:\Projects
Joining Paths
Instead of manually writing separators:
folder = "Projects"
file = "report.pdf"
path = os.path.join(folder,file)
print(path)
Output (Windows)
Projects\report.pdf
Output (Linux/macOS)
Projects/report.pdf
os.path.join() creates platform-independent paths.
Working with Environment Variables
import os
print(os.environ.get("USERNAME"))
Example Output
Rahul
Environment variables store system configuration information.
Executing System Commands
import os
os.system("dir")
Windows displays directory contents.
On Linux/macOS:
os.system("ls")
Real-World Example 1: Student Project Folder
import os
student = "Rahul"
os.mkdir(student)
print("Folder Created")
Real-World Example 2: AI Dataset Organizer
import os
folders = [
"Images",
"Labels",
"Models"
]
for folder in folders:
os.mkdir(folder)
Real-World Example 3: Backup System
import os
if not os.path.exists("Backup"):
os.mkdir("Backup")
Real-World Example 4: Report Generator
import os
report = os.path.join(
"Reports",
"Report1.pdf"
)
print(report)
Common Mistakes
Forgetting to Check File Existence
Incorrect
os.remove("report.pdf")
Correct
if os.path.exists("report.pdf"):
os.remove("report.pdf")
Hardcoding File Paths
Avoid
"C:\\Users\\Rahul\\Desktop"
Prefer
os.path.join()
for cross-platform compatibility.
Removing Non-Empty Directories
os.rmdir() removes only empty directories.
For non-empty directories, use the shutil module (covered in advanced file management).



