1. Introduction
The os module provides a portable way to interact with the operating system, including working with directories, file paths, environment variables, and process information. It abstracts away differences between operating systems like Windows, Linux, and macOS so the same code can run everywhere.
Cricket analogy: The os module is like an ICC standard that lets the same match rules apply whether the game is played in India, England, or Australia, abstracting away local ground quirks while managing directories, paths, and environment info.
Common uses of the os module include creating and removing directories, listing files, checking whether a path exists, and building file paths in a platform-independent way.
Cricket analogy: Common os module tasks are like a groundskeeper creating new practice-net directories, removing old ones, listing which pitches exist, and checking whether a specific net is available before booking it.
2. Syntax
import os
os.getcwd() # current working directory
os.listdir(path) # list entries in a directory
os.mkdir(path) # create a single directory
os.makedirs(path, exist_ok=True) # create nested directories
os.remove(path) # delete a file
os.rmdir(path) # remove an empty directory
os.path.join(a, b) # build a platform-correct path
os.path.exists(path) # check if a path exists
os.path.isfile(path) # check if path is a file
os.path.basename(path) # last component of a path3. Explanation
The os.path submodule handles path manipulation, such as joining directory and file names correctly regardless of operating system (using '/' on Linux/macOS and '\\' on Windows). Functions like os.path.exists(), os.path.isfile(), and os.path.isdir() let you check a path's status before acting on it.
Cricket analogy: os.path is like a scorer joining a venue name and match date into a correct filename regardless of whether the scoreboard system uses '/' or '\\'; functions like os.path.exists() check whether a specific match report file is already saved before overwriting it.
Modern Python code often uses the pathlib module (Path objects) as a more object-oriented alternative to os.path, but os and os.path remain extremely common, especially in existing codebases and simple scripts.
Cricket analogy: Modern scoring apps often use pathlib's object-oriented 'Path' style like a digital scorecard app replacing paper sheets, but many stadiums still rely on the older os.path-style ledger system, especially for legacy record-keeping.
os.path functions use plain strings, while pathlib represents paths as Path objects with methods like .exists() and operators like '/' for joining. Both achieve similar goals; os.path is the older, string-based API, and pathlib is the newer, more expressive one.
4. Example
import os, tempfile
base = tempfile.gettempdir()
demo_dir = os.path.join(base, 'demo_os_module')
os.makedirs(demo_dir, exist_ok=True)
file_path = os.path.join(demo_dir, 'sample.txt')
with open(file_path, 'w') as f:
f.write('sample')
print(os.path.exists(file_path))
print(os.path.isfile(file_path))
print(os.path.basename(file_path))
print(os.listdir(demo_dir))
os.remove(file_path)
os.rmdir(demo_dir)
print(os.path.exists(demo_dir))5. Output
True
True
sample.txt
['sample.txt']
False6. Key Takeaways
- The os module provides portable access to operating system features like directories, paths, and environment variables.
- os.path.join() builds file paths correctly across different operating systems.
- os.makedirs(path, exist_ok=True) safely creates nested directories without raising an error if they already exist.
- os.path.exists(), isfile(), and isdir() let you safely check a path before using it.
- pathlib is a newer, object-oriented alternative to os.path for path manipulation.
Practice what you learned
1. Which function should you use to join directory and file names in a platform-independent way?
2. What does os.makedirs(path, exist_ok=True) do differently from os.mkdir(path)?
3. Which function checks whether a given path points to an existing file (not a directory)?
4. What is the modern object-oriented alternative to os.path for handling file paths?
5. Which function returns a list of the names of entries inside a directory?
Was this page helpful?
You May Also Like
File Handling in Python
Understand how to open, read, write, and close files in Python using the built-in open() function and file modes.
Modules and Packages in Python
Learn how Python organizes code into reusable modules and packages, and how the import system locates and caches them.
with Statement (Context Managers) in Python
Learn how the 'with' statement uses the context manager protocol (__enter__/__exit__) to guarantee cleanup, such as automatically closing files.
Reading and Writing Files in Python
Explore the different methods for reading and writing file content, including read(), readline(), readlines(), write(), and writelines().
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics