Python Modules & Packages
Python os and sys Modules
The os module lets Python talk to your operating system's files and folders, while sys gives you access to command-line arguments and interpreter-level settings.
The os Module: Working With Your File System
The os module bridges Python and your operating system, letting you find your current folder, list files, read environment variables, and build file paths that work correctly on Windows, macOS, and Linux alike.
Finding and Listing the Current Folder
os.getcwd() returns your current working directory as a string, and os.listdir() lists every file and folder inside a given directory.
import os
print(os.getcwd())
print(os.listdir("."))Building File Paths With os.path
Rather than joining folder names and filenames with plain strings, os.path.join() builds correct paths automatically for whichever operating system your code runs on.
file_path = os.path.join("data", "students.csv")
print(file_path)
print(os.path.exists(file_path))Reading Environment Variables
os.environ acts like a dictionary of environment variables set on your machine, often used to safely store secrets like API keys outside of your source code.
print(os.environ.get("HOME"))The sys Module: Talking to the Interpreter
While os deals with the operating system, sys deals with the Python interpreter itself — reading command-line arguments, stopping a script early, or inspecting where Python looks for modules.
Reading Command-Line Arguments With sys.argv
sys.argv is a list of the arguments typed after your script's name on the command line, with the script name itself always at index 0.
import sys
name = sys.argv[1]
print(f"Hello, {name}!")python greet.py PriyaExiting a Script and Checking sys.path
sys.exit() stops a program immediately, optionally with an exit code, while sys.path lists the folders Python searches through when you write an import statement.
import sys
if len(sys.argv) < 2:
print("Missing an argument!")
sys.exit(1)
print(sys.path)Use os for anything involving files, folders, and paths, and use sys for anything involving the running script or interpreter itself.
