OS Module

The os module lets your Python programs interact with the operating system - handling file paths, directories, and environment variables in a way that works consistently across Windows, macOS, and Linux.

Working with Directories

import os

print(os.getcwd())          # current working directory
print(os.listdir("."))      # list files/folders in current directory

os.mkdir("new_folder")      # create a new directory
os.rename("old.txt", "new.txt")   # rename a file

Working with File Paths

The os.path submodule handles file paths safely across different operating systems, avoiding manual string concatenation that could break depending on the OS.

import os

full_path = os.path.join("data", "sales", "report.csv")
print(full_path)   # data/sales/report.csv (or data\sales\report.csv on Windows)

print(os.path.exists(full_path))     # True/False
print(os.path.basename(full_path))   # report.csv
print(os.path.splitext(full_path))   # ('data/sales/report', '.csv')

Environment Variables

import os
print(os.environ.get("PATH"))   # read an environment variable safely
Always use os.path.join() instead of manually joining folder and file names with slashes - it automatically uses the correct separator for whichever operating system your code runs on.

Coming Up Next

Next, you'll explore the math module - Python's built-in toolkit for mathematical operations beyond basic arithmetic.

Ready to Master Data Science?

Join Uncodemy's Data Science Course and build real, job-ready skills with expert mentors.

Explore Course