100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Python

os Module in Python

Explore Python's os module for interacting with the operating system, including file paths, directories, and environment information.

Modules, Files & IterablesBeginner8 min readJul 7, 2026
Analogies

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

python
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 path

3. 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

python
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

text
True
True
sample.txt
['sample.txt']
False

6. 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

Was this page helpful?

Topics covered

#Python#PythonProgrammingStudyNotes#Programming#OsModuleInPython#Module#Syntax#Explanation#Example#StudyNotes#SkillVeris