The ability to interface with the operating system is what sets a basic Python script apart from a professional-grade application. The os module in Python is like a Swiss Army knife for doing things at the system level. This module lets you use operating system-dependent features in a portable way, whether you’re automating file backups, making directories, or managing environment variables.
Even if higher-level libraries like pathlib are becoming more popular, the os module in Python will still be important for system administrators, DevOps engineers, and data scientists in 2026. We at PW Skills stress that knowing the “Operating System” (the os module in Python) is very important for making software that works perfectly on Windows, macOS, and Linux.
What is the OS Module in Python?
The os module in Python has functions that let you work with the operating system. It lets Python scripts do things that the command prompt or terminal ordinarily does.
Why Use the OS Module?
- Cross-Platform Compatibility: It automatically takes care of the fact that Windows uses \ and Linux/macOS uses /.
- Automation: It lets you make, delete, and move thousands of files in only a few seconds.
- Environment Management: It lets scripts read “secrets” or configuration paths from the system environment.
To get started, you don’t need to install anything. The module is built-in; simply use import os.
Navigation and Directory Management in OS Module in Python
The most common use for the os module in python example is managing the “working directory”, the folder where your script is currently looking for files.
2.1 Getting and Changing the Working Directory
- os.getcwd(): Returns the Current Working Directory (CWD).
- os.chdir(path): Changes the CWD to the specified path.
Python
import os
# Where am I?
print(“Before:”, os.getcwd())
# Move to a different folder
os.chdir(“../”)
print(“After:”, os.getcwd())
2.2 Listing Files and Directories
The os.listdir() function returns a list of all files and folders in a specified path. This is the foundation of any file-searching script.
Python
files = os.listdir(‘.’) # List everything in the current folder
for f in files:
print(f”Found: {f}“)
Creating and Deleting Directories using OS Module in Python
Managing folders via a script is much safer and faster than doing it manually.
3.1 Creating Folders
- os.mkdir(): Creates a single directory.
- os.makedirs(): Creates a directory and all necessary intermediate-level parent directories (recursive creation).
Python
# Create a single folder
os.mkdir(“Project_Data”)
# Create a nested path (Data -> 2026 -> March)
os.makedirs(“Data/2026/March”)
3.2 Removing Folders
- os.rmdir(): Deletes an empty directory.
- os.removedirs(): Recursively deletes empty parent directories.
Warning: Neither of these functions will delete a folder if it contains files. For that, you would typically use the shutil module.
File Operations and Metadata using OS Module in Python
The os module in python is widely used to rename, move, and inspect files.
4.1 Renaming and Deleting Files
Python
# Rename ‘old.txt’ to ‘new.txt’
os.rename(“old.txt”, “new.txt”)
# Delete a file
os.remove(“temporary_log.txt”)
4.2 Checking File Information
The os.stat() function provides detailed metadata about a file, such as its size and last modification time.
Python
info = os.stat(“report.pdf”)
print(f”Size: {info.st_size} bytes”)
print(f”Last Modified: {info.st_mtime}“)
Path Manipulations with os.path in python
A subset of the module, os.path, is so important that it is often discussed as a separate entity. It provides functions to parse and verify file paths.
| Function | Purpose |
| os.path.join(a, b) | Combines paths using the correct slash for the OS. |
| os.path.exists(path) | Checks if a file or folder actually exists. |
| os.path.isfile(path) | Returns True if the path is a file (not a folder). |
| os.path.basename(path) | Extracts the filename from a full path. |
| os.path.split(path) | Splits a path into (folder_path, filename). |
Advanced Usage: Executing Shell Commands using OS Module in Python
You might need to run a terminal command (like ping or ipconfig) instead of just Python. You can run any command in the system shell with the os.system() method.
Python
# Clear the terminal screen (works on Windows)
os.system(‘cls’)
# List files using the system’s own command
os.system(‘dir’)
Note: The OS module in Python documentation advocates using the subprocess module for more complicated shell interactions in current applications since it gives you more control over input and output.
Managing Environment Variables
People typically utilise environment variables to keep private information safe, such database passwords or API credentials. You may get to these through the os.environ object.
Python
# Get the ‘PATH’ variable
path_var = os.environ.get(‘PATH’)
# Access a custom API key you’ve set on your system
api_key = os.environ.get(‘MY_SECRET_KEY’)
Essential OS Functions
Let’s have a quick understanding about the OS functions and how do they function.
| Category | Function | Description |
| Navigation | getcwd() | Get current working directory. |
| Directory | mkdir() | Create a directory. |
| File | remove() | Delete a file. |
| Metadata | stat() | Get file status/size. |
| Path | path.join() | Join path components safely. |
| Process | system() | Execute a shell command. |
Conclusion
If you want to build strong, automated systems, you have to master the OS module in Python. This module connects your code to the computer it runs on. It lets you do everything from simple directory navigation to managing sophisticated environment variables.
You can locate an OS module in Python PDF or online OS module in Python documentation, but the easiest way to learn is to do it. We at PW Skills propose that you try writing a script that sorts your “Downloads” folder by moving files with different extensions (.pdf, .jpeg, .txt) into subfolders. It’s a classic OS module in python example that will solidify your understanding instantly!
FAQs
What does the complete name of the os module in Python mean?
It means "Operating System Module." It lets you use features that depend on the operating system in a portable way.
Is os.path not the same as the os module?
OS.path is a part of the os module. Os.path is more about strings and path logic, such joining names and verifying if they exist, while os is more about actions, like making folders and deleting files.
Is it possible to read the contents of a file with the OS module?
No. You can read a file's contents with Python's built-in open() method. Use the os module to find the file or check its size, and open() to view what's inside.
Why is it better to use os.path.join() than just adding strings together?
If you use folder + "/" + file, your code will break on Windows. os.path.join() automatically figures out whether to use / or \ based on the user's operating system.
Is there a newer version of the OS module?
Yes, the pathlib module, which was added to Python 3.4, lets you work with paths in an object-oriented way. But for some low-level system tasks, the os module is still faster and is used all the time in old code.
