🗂️ Python Tutorial — OS Module

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

💡 Used in automation, scripting, file management, server tasks, and system-level programming
💡 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

⚠️ Make sure the path exists, or you'll get an error.

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 folder

removedirs.py

os.removedirs("parent/child/grandchild")

Note

⚠️ Only removes empty directories.

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"))
FunctionPurpose
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

⚠️ File must exist or you'll get FileNotFoundError.

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

⚠️ Use carefully — executes commands on your OS

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 bytes

17. 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 📘

ActionFunction
Get current directoryos.getcwd()
Change directoryos.chdir()
List directoryos.listdir()
Create/remove folderos.mkdir(), os.rmdir()
Join pathsos.path.join()
Split pathos.path.split()
Renameos.rename()
Delete fileos.remove()
Environmentos.getenv(), os.environ
Walk directoryos.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 🎉

>>“The OS module connects Python with your operating system — empowering scripts, automation, and real-world applications.” ✨

You now fully understand the OS module! Want the next topic? Try Sys, Pathlib, Shutil, Pickle, or Subprocess. Just tell me! 😊