Python OS Module: A Complete Guide for Beginners

Introduction Of Python OS Module

When writing Pythons programs, one of the biggest challenges is ensuring they run smoothly on different operating systems like Windows, macOS, or Linux. That’s where the Python os module comes in. It acts as a bridge between Python and your operating system, giving you tools to manage files, directories, environment variables, and even system commands.

In this blog, we’ll explore the most useful features of the Python os module with examples.

1. Directory Operations with Pythons OS Module

Organizing files manually can be tiring. With the os module, you can create folders, list their contents, and remove them automatically.

import os

# Create a folder for PDFs if not already present
if not os.path.exists("pdfs"):
    os.mkdir("pdfs")

# Create nested directories for images
os.makedirs("images/2025/events", exist_ok=True)

# List everything in the current directory
print("Contents:", os.listdir("."))

# Remove an empty folder
os.rmdir("old_folder")
Code language: PHP (php)

os.mkdir() creates a single folder, while os.makedirs() allows creating nested folders. exist_ok=True ensures no error if the folder already exists.

2. Navigating the Filesystem in Python OS Module

Instead of hardcoding paths, you can change the working directory dynamically.

import os

print("Current directory:", os.getcwd())

os.chdir("logs")  
print("Inside logs:", os.getcwd())

print("Log files:", os.listdir("."))

os.chdir("..")  
print("Back to:", os.getcwd())
Code language: PHP (php)

os.getcwd() returns the current directory, and os.chdir() changes it. This makes your scripts flexible and portable.

3. Handling File Paths Across Operating Systems in Python OS Module

File paths vary depending on the OS (C:\Users on Windows vs /home/ on Linux). The os.path module helps build cross-platform file paths safely.

import os

folder = "reports"
filename = "summary.txt"
path = os.path.join(folder, filename)

print("Full path:", path)
print("Absolute path:", os.path.abspath(path))

directory, file = os.path.split(path)
print("Directory:", directory)
print("File:", file)

name, ext = os.path.splitext(file)
print("Name:", name)
print("Extension:", ext)
Code language: PHP (php)

Using os.path.join() ensures correct path formatting, regardless of your OS.

4. Managing File Permissions in Pythons OS Module

Sometimes, you may want to make files read-only or executable.

import os, stat

file_path = "example.txt"

if os.access(file_path, os.R_OK) and os.access(file_path, os.W_OK):
    print("File is readable and writable")

os.chmod(file_path, stat.S_IREAD)  
print("File is now read-only")

os.chmod(file_path, stat.S_IREAD | stat.S_IEXEC)  
print("File is now executable")
Code language: PHP (php)

The stat module works with permission constants like S_IREAD (read-only), S_IWRITE (writable), and S_IEXEC (executable).

5. Using Environment Variables in Python OS Module

Instead of storing API keys or sensitive information inside your script, use environment variables.

import os

api_key = os.getenv("API_KEY")

if api_key:
    print("API Key found:", api_key[:4] + "****")
else:
    print("API Key not found")

os.environ["MODE"] = "development"
print("Mode:", os.environ["MODE"])
Code language: PHP (php)

os.getenv() retrieves environment variables safely, and os.environ allows you to set them during execution.

6. Running System Commands in Python OS Module

You can run system-level commands directly from Python.

import os

os.system("date")  

# Clear the terminal screen
os.system("cls" if os.name == "nt" else "clear")
Code language: PHP (php)

And for cleaning temporary files:

import os

if os.name == "nt":
    os.system("del temp\\*.tmp")
else:
    os.system("rm temp/*.tmp")
Code language: JavaScript (javascript)

Note: os.system() is simple but not secure for production. For advanced use, prefer the subprocess module.

7. Getting System Information

The os module can also provide system-related details.

import os

print("OS Name:", os.name)
print("Process ID:", os.getpid())
print("Parent Process ID:", os.getppid())
print("User:", os.getlogin())
print("CPU Count:", os.cpu_count())
Code language: CSS (css)

On Unix-based systems, os.uname() gives additional system details.

8. Traversing a Directory Tree

Searching for files manually in nested folders is slow. Instead, use os.walk() to scan all subdirectories.

import os

search_dir = "project"
target_ext = ".log"

for dirpath, dirnames, filenames in os.walk(search_dir):
    for file in filenames:
        if file.endswith(target_ext):
            print("Found:", os.path.join(dirpath, file))
Code language: JavaScript (javascript)

This is especially useful for scanning logs, images, or data files across large projects.

Conclusion

The Python os module is one of the most versatile standard libraries. It helps you:

  • Automate file and folder management
  • Navigate directories easily
  • Handle paths across different operating systems
  • Securely manage permissions and environment variables
  • Run system commands and gather system info
  • Traverse directory trees efficiently

If you’re building real-world Python applications, mastering the os module is a must. It makes your code cleaner, portable, and more powerful.

👉 Subscribe to the Tech Naukary WhatsApp channel now to receive real-time alerts about internship updates 2025, latest exam results 2025, government job updates, and scholarship deadlines. Let us guide you every step of the way!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top