Introduction 🌟
The os module in Python provides functions to interact with the operating system. It allows you to manage files, directories, system paths, process information, and environment variables.
Note
💡 Cross-platform: works on Windows, macOS, Linux
1. Importing the OS Module 🧱
import_os.py
import os✔ Now you're ready to interact with the operating system
2. Getting Current Working Directory 📍
cwd.py
import os
print(os.getcwd())✔ Returns the folder where the script is running
3. Changing Directory 📂
chdir.py
os.chdir("C:/Users/Sathish/Desktop")Note
4. Listing Files & Folders 📁
listdir.py
files = os.listdir(".")
print(files)✔ Lists all files/directories in the given path
5. Creating Directories 🏗️
mkdir.py
os.mkdir("myfolder")makedirs.py
os.makedirs("parent/child/grandchild")✔ mkdir → creates one folder
✔ makedirs → creates nested folder structure
6. Removing Directories 🗑️
rmdir.py
os.rmdir("myfolder") # remove empty folderremovedirs.py
os.removedirs("parent/child/grandchild")Note
7. Checking If a Path Exists ✔️❌
path_exists.py
print(os.path.exists("myfile.txt"))8. Joining Paths Safely 🔗
path_join.py
path = os.path.join("folder", "subfolder", "file.txt")
print(path)✔ Automatically uses the correct separator ("/" or "\")
✔ Cross-platform safe
9. Splitting File Path 🪓
path_split.py
print(os.path.split("folder/file.txt"))splitext.py
print(os.path.splitext("file.txt"))| Function | Purpose |
|---|---|
| os.path.split() | Splits into (path, filename) |
| os.path.splitext() | Splits filename & extension |
10. Renaming Files & Folders ✏️
rename.py
os.rename("old.txt", "new.txt")✔ Works for both files and directories
11. Removing Files 🧽
remove.py
os.remove("file.txt")Note
12. Get Environment Variables 🌍
getenv.py
print(os.getenv("PATH"))13. Set Environment Variables (Temporary) 🧪
setenv.py
os.environ["APP_MODE"] = "production"
print(os.environ["APP_MODE"])✔ Useful for config, secrets, deployment
14. Execute System Commands ⚙️
system_command.py
os.system("echo Hello World")Note
15. Walk Through a Directory Tree 🌲
os_walk.py
for root, dirs, files in os.walk("C:/Users/Sathish"):
print("Root:", root)
print("Dirs:", dirs)
print("Files:", files)
print()✔ Powerful for indexing, backups, search tools
16. Get File Size 📏
file_size.py
print(os.path.getsize("file.txt")) # in bytes17. Check File or Directory Type 📂📄
is_file_dir.py
print(os.path.isfile("file.txt"))
print(os.path.isdir("myfolder"))18. Real-World Example — Clean Temporary Files 🧹
cleanup_example.py
import os
folder = "temp"
for file in os.listdir(folder):
path = os.path.join(folder, file)
if os.path.isfile(path):
os.remove(path)
print("Deleted:", path)✔ Used in automation scripts
19. Real-World Example — Directory Size Calculator 📦
dir_size_example.py
def folder_size(path):
size = 0
for root, dirs, files in os.walk(path):
for f in files:
size += os.path.getsize(os.path.join(root, f))
return size
print(folder_size("."))20. OS Module Cheat Sheet 📘
| Action | Function |
|---|---|
| Get current directory | os.getcwd() |
| Change directory | os.chdir() |
| List directory | os.listdir() |
| Create/remove folder | os.mkdir(), os.rmdir() |
| Join paths | os.path.join() |
| Split path | os.path.split() |
| Rename | os.rename() |
| Delete file | os.remove() |
| Environment | os.getenv(), os.environ |
| Walk directory | os.walk() |
Best Practices 💡
- ✔ Use os.path.join for safe path building
- ✔ Always check os.path.exists before operations
- ✔ Avoid using os.system unless necessary
- ✔ Prefer pathlib for modern path handling
Conclusion 🎉
You now fully understand the OS module! Want the next topic? Try Sys, Pathlib, Shutil, Pickle, or Subprocess. Just tell me! 😊