OS Module
The os module is part of Python's standard library and provides a portable way to interact with the operating system. It exposes functions for working with...
Using the Python os Module for System Operations
The os module is part of Python's standard library and provides a portable way to interact with the operating system. It exposes functions for working with environment variables, processes, file permissions, and most importantly, the filesystem. Because it abstracts platform differences, code that uses os usually works on Windows, macOS, and Linux without modification.
To use the module, you simply import it. There is no installation required:
import os
print(os.getcwd()) # Current working directory os.chdir("/tmp") # Change working directory print(os.listdir(".")) # List files in current directory
The os.path submodule is one of the most commonly used parts of os. It provides functions for manipulating file paths as strings. os.path.join() builds a path from components in a platform-safe way, automatically using the right separator (backslash on Windows, forward slash on Unix). os.path.exists() checks whether a file or directory exists. os.path.isfile() and os.path.isdir() distinguish between files and directories.
import os
base = "/home/user" filename = "data.txt" full_path = os.path.join(base, filename) print(full_path) # /home/user/data.txt print(os.path.exists(full_path)) # True or False
For directory operations, os.mkdir() creates a single new directory, while os.makedirs() creates an entire directory tree. The exist_ok=True parameter prevents an error if the directory already exists. os.remove() deletes a file, and os.rmdir() removes an empty directory. For removing non-empty directories, use shutil.rmtree() from the shutil module.
Environment variables are accessible through os.environ, which behaves like a dictionary. You can read a variable with os.environ.get("HOME") or os.getenv("HOME"), with the second argument serving as a default if the variable is not set.
import os path = os.getenv("PATH", "not set")
The os.rename() function renames or moves files, and os.stat() returns metadata such as file size, permissions, and modification time.
Interview tip: Know that os.path.join() is the correct way to build paths, not string concatenation with "/" or "\\". This matters because Windows uses backslashes. Mention that the pathlib module (introduced in Python 3.4) is the modern alternative to os.path and offers a more object-oriented API.