Skip to content

Common Python Libraries

Python has a huge collection of libraries that add extra powers to the language. These libraries let you do things like talk to the internet, save data to a database, build websites, and much more - without writing everything from scratch yourself.

These libraries show up in real projects, job interviews, and everyday development work.

LibraryMain Use
osOS operations, file system tasks, environment variables
sysPython runtime info, command-line arguments, exits
typingType hints for better code clarity, IDE support, and error catching
jsonConvert Python data to/from JSON
csvRead and write CSV files
sqlite3Lightweight embedded SQL database
requestsHTTP client for APIs and web calls
datetimeDates, times, formatting, arithmetic
pathlibModern and clean path/file handling
python-dotenvLoad environment variables from .env
loggingStructured application logs
flaskBuild simple web applications and APIs
tkinterBuild desktop GUI applications
graph TD Core["Python App"] --> FS["os + pathlib"] Core --> Runtime["sys"] Core --> Types["typing"] Core --> Data["json + csv"] Core --> DB["sqlite3"] Core --> HTTP["requests"] Core --> Time["datetime"] Core --> Config["python-dotenv"] Core --> Logs["logging"] Core --> Web["flask"] Core --> GUI["tkinter"]

Official docs: https://docs.python.org/3/library/os.html

Use os when you need to talk directly to the operating system - things like checking folders, deleting files, or reading environment variables.

  • Working with directories and files
  • Reading environment variables
  • Getting info about the current process
  • os.getcwd() -> get the current working directory
  • os.listdir(path) -> list everything inside a folder
  • os.makedirs(path, exist_ok=True) -> create folders without crashing if they already exist
  • os.remove(path) -> delete a file
  • os.environ.get("KEY") -> safely read an environment variable
import os
print("Current directory:", os.getcwd())
os.makedirs("data/output", exist_ok=True)
api_key = os.environ.get("API_KEY")
print("API key loaded:", bool(api_key))
  • Prefer pathlib for file path work in new code - it’s cleaner
  • Use os.environ.get() instead of os.environ["KEY"] to avoid a KeyError crash when the variable doesn’t exist

Official docs: https://docs.python.org/3/library/sys.html

Use sys when you want to read arguments passed to your script, exit the program, or check which version of Python is running.

  • Read values the user passes when running your script
  • Stop the program and return an exit code
  • Check the Python version or module search paths
  • sys.argv -> list of arguments passed to the script
  • sys.exit(code) -> stop the program (0 = success, anything else = error)
  • sys.version -> the current Python version as a string
  • sys.path -> list of folders Python searches when importing modules
import sys
if len(sys.argv) < 2:
print("Usage: python app.py <name>")
sys.exit(1)
name = sys.argv[1]
print(f"Hello, {name}")
  • Always check that the right number of arguments were passed before using them
  • Use a non-zero exit code (like 1) when something goes wrong, so other programs or scripts can detect the failure

Official docs: https://docs.python.org/3/library/typing.html

Use typing to add labels to your code that say what type of data a variable or function should work with. These labels are called type hints.

  1. Catches errors early - IDEs and type checkers can spot bugs before you even run the code
  2. Self-documenting code - other developers can understand what your functions expect without reading extra docs
  3. Better IDE support - autocomplete and suggestions work much better
  4. Enables static analysis - tools like mypy can check your code for type mistakes without running it
  5. Improves maintainability - it’s easier to change and refactor code when types are clearly written out
  • int, str, float, bool -> basic built-in types
  • List[int] -> a list that contains integers
  • Dict[str, int] -> a dictionary with string keys and integer values
  • Tuple[str, int] -> a tuple with a string and then an integer
  • Optional[str] -> a string, or None
  • Union[str, int] -> can be either a string or an integer
  • Callable[[int, str], bool] -> a function that takes an int and a str and returns a bool
  • Any -> any type at all (try not to use this too much)
from typing import List, Dict, Optional
def greet(name: str, age: int) -> str:
"""Greet a person with their age."""
return f"Hello {name}, you are {age} years old"
def find_user(user_id: int) -> Optional[Dict[str, str]]:
"""Return user data or None if not found."""
users = {1: {"name": "Alice"}, 2: {"name": "Bob"}}
return users.get(user_id)
def process_scores(scores: List[int]) -> float:
"""Calculate average score."""
return sum(scores) / len(scores) if scores else 0.0
# Function calls
print(greet("Sahil", 25))
print(find_user(1))
print(process_scores([85, 90, 78]))
from typing import List, Dict, Tuple, Union, Callable
# A list of dictionaries (common with API responses)
users: List[Dict[str, Union[str, int]]] = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 30},
]
# Tuple with fixed types
coordinates: Tuple[float, float] = (10.5, 20.3)
# Callback function type
process_callback: Callable[[str], int] = lambda x: len(x)
# Optional values (might be None)
api_key: Optional[str] = None
from typing import List, Optional
class User:
def __init__(self, name: str, email: str) -> None:
self.name: str = name
self.email: str = email
self.posts: List[str] = []
def add_post(self, title: str) -> None:
"""Add a post to user's list."""
self.posts.append(title)
def get_email(self) -> str:
return self.email
user = User("Sahil", "sahil@example.com")
user.add_post("My First Post")

Install mypy to check your types without running your code:

Terminal window
uv add --dev mypy
uv run mypy your_file.py

mypy will catch mistakes like this:

# This will be flagged by mypy
name: str = "Alice"
age: int = name # Error: incompatible types (str vs int)
  • Add type hints to function parameters and return values
  • Use Optional[T] when a value might be None, not Optional[Union[T, None]] - they mean the same thing but Optional[T] is cleaner
  • Use List, Dict, Tuple from typing for Python versions below 3.9, or just use the built-in list, dict for Python 3.9 and above
  • Keep your types simple and easy to read - avoid making them too complex
  • Type hints are optional, but strongly recommended for any code that others will use or maintain

Official docs: https://docs.python.org/3/library/json.html

json lets you convert Python data (like dictionaries and lists) into JSON text, and turn JSON text back into Python data. This is very common when working with APIs.

  • json.dumps(obj) -> turn a Python object into a JSON string
  • json.loads(text) -> turn a JSON string into a Python object
  • json.dump(obj, file) -> write JSON directly into a file
  • json.load(file) -> read JSON from a file
import json
user = {"name": "Sahil", "active": True, "score": 91}
# To string
payload = json.dumps(user, indent=2)
print(payload)
# To file
with open("user.json", "w", encoding="utf-8") as f:
json.dump(user, f, indent=2)
  • Use indent=2 to make the JSON file easy to read
  • Use ensure_ascii=False if your data has non-English characters
  • Remember that JSON only supports basic types - dict, list, str, int, float, bool, and null (which becomes None in Python)

Official docs: https://docs.python.org/3/library/csv.html

csv is for working with spreadsheet-style data where values are separated by commas. This format is very common for exporting and sharing data.

  • csv.reader() / csv.writer() - work with rows as plain lists
  • csv.DictReader() / csv.DictWriter() - work with rows as dictionaries using column names
import csv
rows = [
{"name": "A", "marks": 85},
{"name": "B", "marks": 92},
]
with open("marks.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["name", "marks"])
writer.writeheader()
writer.writerows(rows)
with open("marks.csv", "r", newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["name"], row["marks"])
  • Always use newline="" when opening CSV files on Windows to avoid getting blank lines between rows
  • Prefer DictReader and DictWriter - using column names makes the code much easier to understand

Official docs: https://docs.python.org/3/library/sqlite3.html

sqlite3 gives you a simple database that lives in a single file on your computer. No server setup needed - it just works.

  • Small to medium local apps
  • Learning SQL and databases
  • Desktop tools or apps that work offline
  1. Connect to the database file
  2. Create a cursor (the tool you use to run SQL)
  3. Run your SQL commands
  4. Commit the changes (save them)
  5. Close the connection
import sqlite3
conn = sqlite3.connect("app.db")
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)")
cur.execute("INSERT INTO users (name) VALUES (?)", ("Sahil",))
conn.commit()
cur.execute("SELECT id, name FROM users")
print(cur.fetchall())
conn.close()
  • Always use parameterized queries with ? placeholders - never put user input directly into SQL strings, as that can cause security problems (SQL injection)
  • Wrap database operations in try/except blocks in real apps so errors don’t crash everything

Official docs: https://requests.readthedocs.io/en/latest/

requests is the most popular Python library for talking to the internet - fetching web pages, calling APIs, sending data, and more.

Terminal window
uv add requests
  • requests.get(url) - fetch data from a URL
  • requests.post(url, json=data) - send data to a URL
  • response.status_code - check if the request succeeded (200 = OK)
  • response.json() - parse the response as JSON
  • response.raise_for_status() - automatically raise an error if the request failed
import requests
url = "https://jsonplaceholder.typicode.com/todos/1"
response = requests.get(url, timeout=10)
response.raise_for_status()
data = response.json()
print(data["title"])
  • Always set a timeout so your program doesn’t hang forever waiting for a response
  • Call raise_for_status() right after the request so you catch HTTP errors (like 404 or 500) straight away
  • Use Session() if you’re making many requests to the same website - it reuses the connection and is faster

Official docs: https://docs.python.org/3/library/datetime.html

Use datetime whenever you need to work with dates, times, or both - like getting the current time, formatting a date for display, or calculating how many days until a deadline.

  • Get the current date/time: datetime.now()
  • Turn a string into a date: datetime.strptime()
  • Turn a date into a string: datetime.strftime()
  • Add or subtract time using timedelta
from datetime import datetime, timedelta
now = datetime.now()
print("Now:", now.strftime("%Y-%m-%d %H:%M:%S"))
deadline = now + timedelta(days=7)
print("Deadline:", deadline.strftime("%Y-%m-%d"))
  • Store times in UTC (a universal time standard) in backend systems to avoid timezone confusion
  • Only convert to the local timezone when you’re showing the time to a user

Official docs: https://docs.python.org/3/library/pathlib.html

pathlib is the modern way to work with file and folder paths in Python. Instead of joining strings together manually, you use Path objects that are much cleaner to read and work with.

  • Build paths by joining them with /
  • Check if a file or folder exists
  • Read and write text files quickly
  • Loop through all files in a folder
from pathlib import Path
base = Path("data")
base.mkdir(exist_ok=True)
file_path = base / "notes.txt"
file_path.write_text("Hello from pathlib\n", encoding="utf-8")
print(file_path.read_text(encoding="utf-8"))
  • Use Path instead of manually joining strings with + or os.path.join()
  • Always specify encoding="utf-8" when reading or writing text files

python-dotenv - Environment Variables from .env

Section titled “python-dotenv - Environment Variables from .env”

Official docs: https://saurabh-kumar.com/python-dotenv/

python-dotenv reads a .env file and loads the values inside it as environment variables. This is a very common way to keep secrets (like API keys) out of your code.

Terminal window
uv add python-dotenv

.env

API_KEY=your_secret_key
DEBUG=true

app.py

from dotenv import load_dotenv
import os
load_dotenv()
api_key = os.getenv("API_KEY")
debug = os.getenv("DEBUG", "false").lower() == "true"
print("Key exists:", bool(api_key))
print("Debug:", debug)
  • Never commit your .env file to Git - add it to .gitignore
  • Never paste API keys or passwords directly into your code - always use environment variables

Official docs: https://docs.python.org/3/library/logging.html

Use logging instead of print() when building real applications. It gives you much more control - you can set levels, add timestamps, write to files, and filter what gets shown.

  • DEBUG -> very detailed info, useful when tracking down a bug
  • INFO -> normal things happening as expected
  • WARNING -> something unexpected happened, but the app is still working
  • ERROR -> something went wrong and a task failed
  • CRITICAL -> something went very wrong and the app may not be able to continue
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)s | %(message)s"
)
logging.info("Application started")
logging.warning("Cache miss for user profile")
logging.error("Database connection failed")
  • Always include a timestamp and log level in your format string
  • Inside except blocks, use logger.exception("...") instead of logger.error(...) - it also prints the full error traceback
  • For apps that run for a long time, write logs to a file so you can check them later

Official docs: https://flask.palletsprojects.com/

flask is a small and beginner-friendly framework for building websites and APIs with Python. It’s a great starting point for learning how web backends work.

Terminal window
uv add flask
  • Flask(__name__) -> creates your app
  • @app.route("/") -> connects a URL to a Python function
  • request -> lets you read data sent by the browser or client
  • jsonify() -> sends back a JSON response
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/")
def home():
return "Hello, Flask!"
@app.route("/api/health")
def health():
return jsonify({"status": "ok"})
if __name__ == "__main__":
app.run(debug=True)
Terminal window
python app.py

Then open http://127.0.0.1:5000 in your browser.

graph TD Browser --> Route["Flask Route"] Route --> Function["Python Function"] Function --> Response["HTML or JSON Response"] Response --> Browser
  • Keep route functions short - move your actual logic into separate functions or files
  • Only use debug=True while developing, never in production
  • Always check and validate user input before doing anything with it

Official docs: https://docs.python.org/3/library/tkinter.html

tkinter is Python’s built-in library for building desktop apps with windows, buttons, and text fields. You don’t need to install anything extra - it comes with Python.

  • Tk() -> creates the main window
  • Widgets like Label, Entry, Button -> the building blocks of your UI
  • command= -> tells a button which function to run when clicked
  • mainloop() -> keeps the window open and listening for user actions
import tkinter as tk
def greet():
name = name_entry.get().strip() or "Friend"
output_label.config(text=f"Hello, {name}!")
app = tk.Tk()
app.title("Greeting App")
app.geometry("320x180")
tk.Label(app, text="Enter your name:").pack(pady=8)
name_entry = tk.Entry(app, width=28)
name_entry.pack(pady=4)
tk.Button(app, text="Greet", command=greet).pack(pady=10)
output_label = tk.Label(app, text="")
output_label.pack(pady=6)
app.mainloop()
graph TD Start --> Window["Create Window"] Window --> Widgets["Add Widgets"] Widgets --> Loop["mainloop()"] Loop --> Click["User Clicks Button"] Click --> Handler["Run command function"] Handler --> Update["Update Label/State"] Update --> Loop
  • Keep button callback functions short and focused on one thing
  • Always check and clean input from Entry fields before using it
  • For bigger desktop apps, split your UI code into classes or separate files to keep things organized