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.

Walking Through Folders to Load Many Files

Data often arrives as dozens of files spread across folders, such as one CSV per month or per store. os.walk() visits every folder under a starting point and gives you three things at each stop: the folder path, its subfolders and its files.

import os
import pandas as pd

frames = []
for folder, subfolders, files in os.walk("data"):
    for name in files:
        if name.lower().endswith(".csv"):
            path = os.path.join(folder, name)
            df = pd.read_csv(path)
            df["source_file"] = name          # remember where each row came from
            frames.append(df)

sales = pd.concat(frames, ignore_index=True)
print(len(frames), "files loaded,", len(sales), "rows in total")

Adding a source_file column is a small habit that pays off later, because when a strange value shows up you can trace it back to the exact file.

Creating Folders, Checking Files and Handling Paths Safely

import os

os.makedirs("output/reports/monthly", exist_ok=True)   # creates every missing level

path = "data/sales/report.csv"
if os.path.isfile(path):
    size_kb = os.path.getsize(path) / 1024
    print(f"{size_kb:.1f} KB")

print(os.path.abspath("data"))     # full path from the current folder
print(os.path.expanduser("~"))     # the user's home folder

# Build paths relative to this script, not to wherever it was started from
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
config_path = os.path.join(BASE_DIR, "config.json")

# Read settings and secrets from the environment, with a default
mode = os.getenv("APP_MODE", "development")
api_key = os.environ.get("API_KEY")
if api_key is None:
    raise RuntimeError("Please set the API_KEY environment variable")

os.mkdir() creates only one folder and fails if it already exists, whereas os.makedirs(..., exist_ok=True) is safe to run again and again, which suits scripts that run every day. Building paths from __file__ means the script finds its files whether you run it from the project folder, a scheduler or an IDE. Keep in mind that __file__ is not defined in Jupyter notebooks, where the notebook's folder is usually the working directory.

Reading keys from environment variables keeps passwords and tokens out of your code and out of version control.

os, pathlib or shutil: Picking the Right Tool

TaskGood choice
Environment variables, process details, walking foldersos
Object-style path handling, such as Path("data") / "sales.csv"pathlib
Copying, moving and deleting whole folder treesshutil
Running other programssubprocess

Newer code often prefers pathlib for paths because it reads naturally, but the os functions remain common and work with the same path strings.

Mistakes to avoid

  • Relying on the current working directory. A relative path such as "data/file.csv" breaks when the script is started from another folder.
  • Deleting carelessly. os.remove() deletes a file permanently, with no recycle bin. Print the list of files first and confirm before deleting in bulk.
  • Using os.system() with user input. Joining text into a shell command can let unexpected input run extra commands. Use subprocess.run() with a list of arguments instead.
  • Assuming file order. os.listdir() and os.walk() do not promise any order. Sort the names when order matters.
  • Typing separators by hand. Writing "data\sales" or "data/" + name works on one system and breaks or confuses on another. Let os.path.join() or pathlib build the path.
  • Listing huge folders slowly. For folders with many thousands of files, os.scandir() is faster because it returns file details along with each name.

Ready to Master Data Science?

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

Explore Course