Python OS Module – Most Needful Practical Examples
These are the most important OS module programs every student must know for real automation.
1. Get Current Working Directory
Used to know where your Python program is running.
import os
print(os.getcwd())
Why needed:
Helps avoid path errors while reading or writing files.
2. Change Working Directory
Move Python execution to another folder.
import os
os.chdir("D:/PythonProjects")
print(os.getcwd())
Why needed:
Used in automation scripts where files are in different folders.
3. Create a Folder
import os
os.mkdir("Reports")
Why needed:
Automatically create folders for storing outputs.
4. Create Multiple Folders
import os
folders = ["Data", "Images", "Docs"]
for f in folders:
os.mkdir(f)
Why needed:
Creates project structure automatically.
5. Check File or Folder Exists
import os
if os.path.exists("Data"):
print("Exists")
else:
print("Not Exists")
Why needed:
Prevents errors before deleting or renaming files.
6. List Files and Folders
import os
print(os.listdir())
Why needed:
Used in file scanning and automation.
7. Rename File or Folder
import os
os.rename("Data", "ProjectData")
Why needed:
Used in organizing files automatically.
8. Delete File
import os
os.remove("sample.txt")
Why needed:
Used in cleaning unwanted files.
9. Delete Empty Folder
import os
os.rmdir("OldReports")
Why needed:
Removes unused folders automatically.
10. Join File Paths Safely
import os
path = os.path.join("Data", "report.txt")
print(path)
Why needed:
Avoids errors between Windows and Linux path formats.
11. Get File Size
import os
print(os.path.getsize("report.txt"))
Why needed:
Used in upload validation and storage management.
12. Scan Folder Completely
import os
for root, folders, files in os.walk("D:/Projects"):
print(root, files)
Why needed:
Used in search engines and backup systems.
13. Find Specific Files
import os
for root, folders, files in os.walk("D:/Projects"):
for file in files:
if file.endswith(".pdf"):
print(os.path.join(root, file))
Why needed:
Used in document management systems.
14. Automatically Delete Old Files
import os, time
folder = "D:/Temp"
now = time.time()
for file in os.listdir(folder):
path = os.path.join(folder, file)
if os.stat(path).st_mtime < now - 7*86400:
os.remove(path)
Why needed:
Used in log cleaners and system maintenance.
15. Real Automation Example – Student Folder Creator
import os
students = ["Ravi", "Priya", "Kumar"]
for name in students:
if not os.path.exists(name):
os.mkdir(name)
Why needed:
Used in schools, colleges and training institutes.
Best Practices for Students
- Always check file or folder exists before deleting
- Never test delete programs in system folders
- Use sample folders for practice
- Use os.path.join for file paths
- Keep automation scripts simple and safe
Summary
These OS module examples are the most required for real Python automation.
Every student must practice these before learning advanced automation libraries.