A Tour of the Python Standard Library: The Ten Groups You Will Actually Use
Python ships with a big toolbox — no pip install needed. This guide tours the ten most useful standard-library groups: paths, counting, looping, dates, JSON, regex, statistics, command-line tools, dataclasses and networking. Every example was actually run on Python 3.12.3, with plain advice on when to use each module and what happens if you don't.

Once you have learned variables, functions, classes, exceptions and file I/O, most beginners ask the same question: what comes next? The answer may surprise you: before installing any third-party library, look at the toolbox that already ships with Python. It is called the standard library.
The standard library is a large set of modules that comes with every Python installation. No pip install, no downloads, no internet needed — just import and use. Counting files, computing averages, reading config files, fetching a web page, building a small command-line tool: the everyday jobs already have ready-made wheels in there. This guide walks you through the most useful ones. For each group I will cover three things: what it does, when to reach for it, and what happens if you do not. Every example was actually run on Python 3.12.3, and every output quoted here is a real result, not something made up from memory.
The running example is a fictional little bookshop, "Morning Light Bookshop": recording sales, doing the sums, writing a daily report. The data is invented; the code and the outputs are real. Type the examples out yourself — you will remember far more than by reading alone.
First, get your bearings: what the standard library looks like
How big is it? The official documentation lists more than two hundred modules, covering text, numbers, dates, files, networking, compression and databases — almost any everyday programming job you can think of. Do not let that number scare you: only twenty or thirty of them see daily use. You do not need to memorise them; you just need to know they exist, so that when a problem shows up you remember to look.
When you meet an unfamiliar module, two tricks help most. First, check the official docs at docs.python.org — search the module name and you will find usage and examples. Second, ask Python itself in an interactive session:
import collections
print(dir(collections)) # see what names this module holds
help(collections.Counter) # read the details of one thing
One rule to keep: import with the full form, import os, not from os import *. The official tutorial warns about this explicitly: a star import dumps every name from the module into your code, where it can silently overwrite your own functions and make bugs hard to find.
The diagram below is the map for this whole guide: ten groups of modules, sorted by the kind of job they do. Keep this picture in your head; each group gets its own section after it.

Group 1: paths and the system — pathlib, os, sys
You cannot write programs without touching files: reading a data file, writing results into a folder, working out which day's report to generate. For paths, the recommended tool is pathlib. Its style is intuitive — join path parts with a slash, like stacking blocks:
from pathlib import Path
p = Path("sales") / "2026-11-23.txt"
print(p) # sales/2026-11-23.txt
print(p.parent) # sales
print(p.suffix) # .txt
print(p.name) # 2026-11-23.txt
That is the real output. A Path object is more than a string: it comes with handy attributes and methods. .parent gives the parent directory, .suffix the extension, .name the file name, .exists() tells you whether the file is there, .read_text(encoding="utf-8") reads the contents, .write_text() writes them. You met it in the file I/O guide already; the point here is to make it your default. New code should reach for pathlib first and build strings by hand as rarely as possible.
What happens without it? The old way is to glue strings together, like "sales" + "/" + "2026-11-23.txt". That works on your own machine, until the code moves to Windows, where slashes point the other way — and spaces or non-ASCII characters in a path make things worse. pathlib hides those system differences, so the same code runs anywhere.
os is the lower-level layer, dealing with the operating system itself: which directory you are in, what the environment variables hold, creating and listing directories. The most used ones are os.getcwd() for the current directory, os.environ.get("HOME") for an environment variable, and os.makedirs("sales", exist_ok=True) for creating directories. One detail: read environment variables with .get(), which returns None when the variable does not exist instead of raising an error. Indexing with square brackets raises KeyError when the variable is missing.
sys deals with the Python interpreter itself. Its most used attribute is sys.argv, which holds the command-line arguments. When you run python3 report.py --day 2026-11-23, sys.argv is ['report.py', '--day', '2026-11-23'] — the first element is always the script's own name. I verified this: running python3 -c "import sys; print(sys.argv)" a b printed ['-c', 'a', 'b'], where the first element became -c because no script file was run. There is also sys.version, which tells you which Python you are running — 3.12.3 on my machine. When something behaves strangely, check the version first; version differences cause a surprising share of confusion.
Remember the split like this: pathlib handles what a path looks like, os handles what the operating system can do, and sys handles the interpreter's own state. For anything path-related, look in pathlib first and only fall back to os when it has no answer.
Group 2: collections — the standard data structures, upgraded
Are lists and dicts enough? Often, yes — but some jobs get wordy with them. collections fills that gap, and four of its tools are the ones you will reach for most.
Counter counts things. To find which product sold best in a week, the manual way needs a loop, a dict, and a check for whether the key exists yet:
from collections import Counter
sales = ["book", "pen", "book", "book", "pen", "bag"]
print(Counter(sales))
# Counter({'book': 3, 'pen': 2, 'bag': 1})
print(Counter(sales).most_common(2))
# [('book', 3), ('pen', 2)]
One line does the counting, and most_common(2) gives the top two sellers directly. It can also count letters in a string: Counter("banana") gives Counter({'a': 3, 'n': 2, 'b': 1}), verified by running it. Word frequencies, votes, stock counts — Counter should be your first thought.
defaultdict is a dict that does not make you check whether a key exists first. To group sales by day, a plain dict needs if day not in by_day: by_day[day] = [] first; defaultdict removes that line:
from collections import defaultdict
by_day = defaultdict(list)
by_day["Mon"].append(120)
by_day["Mon"].append(80)
print(dict(by_day)) # {'Mon': [120, 80]}
When you access a missing key, it builds a default value with the factory function you gave it — an empty list for list, 0 for int. Note that it only helps when the key is missing; once a key exists it behaves exactly like a normal dict.
deque is a double-ended queue: fast to add and remove at both ends. Its most common use is "keep only the last few":
from collections import deque
q = deque(maxlen=3)
for i in range(5):
q.append(i)
print(list(q)) # [2, 3, 4]
With maxlen=3, adding the fifth item pushes the oldest one out, leaving 2, 3 and 4. Use it for recent-action logs, sliding windows and queues. By the way, inserting or deleting at the head of a plain list is slow, and the difference shows once the data grows — deque exists for exactly that case.
namedtuple is a "tuple with names". A book in the shop has a title and a price; stored as a plain tuple it is ("Python Basics", 59.9), and fetching the price means writing [1] — come back in two months and you will have to guess what 1 meant:
from collections import namedtuple
Book = namedtuple("Book", ["title", "price"])
b = Book("Python Basics", 59.9)
print(b) # Book(title='Python Basics', price=59.9)
print(b.price) # 59.9
It is still a tuple — it unpacks, compares and uses little memory — but you can also access fields by name. When a data structure is simple, its fields are fixed, and it needs no methods, namedtuple is far lighter than writing a class. When you start needing methods, default values or type checks, move on to the dataclasses group below.
Group 3: itertools and functools — making loops and functions easier
These two are about writing less and running faster. itertools first: it handles all kinds of fancy looping.
chain stitches several sequences together to iterate over as one, without building a big list first:
import itertools
print(list(itertools.chain([1, 2], [3, 4])))
# [1, 2, 3, 4]
print(list(itertools.combinations(["a", "b", "c"], 2)))
# [('a', 'b'), ('a', 'c'), ('b', 'c')]
combinations gives combinations: picking any two letters from three gives three results, and order does not count as a different result. permutations is the other half: list(itertools.permutations("ab")) gives [('a', 'b'), ('b', 'a')] — order does count there. For pairings, sampling and small exhaustive searches, these two are far clearer than hand-written nested loops.
count and islice work well as a pair: count(10) is a sequence that counts up from 10 forever, and islice cuts the first three items out of it:
print(list(itertools.islice(itertools.count(10), 3)))
# [10, 11, 12]
An endless sequence sounds scary, but it is lazy — it produces one number at a time and never fills your memory. When should you reach for itertools? Whenever you catch yourself writing three nested loops, or building one big list just to process it once — stop and check whether a ready-made tool exists.
functools works on functions themselves. Its best-known tool is lru_cache, which gives a function a memory: compute something once for a given argument, and the second call reuses the stored result. The Fibonacci sequence shows the difference best:
import functools
@functools.lru_cache(maxsize=None)
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(10)) # 55
print(fib.cache_info())
# CacheInfo(hits=8, misses=11, maxsize=None, currsize=11)
Without the cache, fib(10) recomputes the same values many times over; with it, every computed value is remembered, and cache_info reports 8 hits and 11 real computations. One condition: arguments must be hashable — passing a list, which is mutable, raises an error. And the cache holds results in memory, so set a maxsize limit if the data is large, or the cache can eat all your memory.
partial "fills in some of a function's arguments in advance" and returns a new function:
from functools import partial
def greet(name, hello="Hello"):
return f"{hello}, {name}"
hi = partial(greet, hello="Hi")
print(hi("Ming")) # Hi, Ming
hi is a customised version of greet where hello is always Hi and only the name is left to fill in. It fits callbacks, sort keys, and any call where a few arguments never change. It reads more clearly than wrapping the call in a one-line lambda, and it is easier to debug when something goes wrong.
Group 4: datetime — do not compute dates by hand
Dates and times are among the easiest things to get wrong by hand: leap years, how many days February has, carrying over month boundaries — hand-rolled arithmetic will trip you up. The datetime module exists to handle that.
import datetime
today = datetime.date(2026, 11, 23)
print(today) # 2026-11-23
print(today.strftime("%Y-%m-%d")) # 2026-11-23
print(today.weekday()) # 0
d = datetime.date(2026, 11, 20)
print((today - d).days) # 3
print(datetime.datetime(2026, 11, 23, 9, 30).isoformat())
# 2026-11-23T09:30:00
A few points: weekday() returns 0 for Monday and 6 for Sunday — a fixed rule, just remember that 0 means Monday. Subtracting two dates gives a timedelta, and .days is the number of days between them: 3. strftime formats a date as a string, where %Y is the four-digit year, %m the month and %d the day; going the other way, strptime parses a string into a date, and datetime.date.fromisoformat("2026-11-23") gives you a date object directly — the daily-report script below depends on it.
Here is an easy mistake to make: what date is one day after 28 February?
print(datetime.date(2026, 2, 28) + datetime.timedelta(days=1))
# 2026-03-01
2026 is not a leap year, so February has 28 days, and adding one day lands on 1 March — the module works it out itself. In the leap year 2024, the same addition gives 29 February. Leave edge cases like this to the module instead of writing if statements yourself.
One more classic trap: datetime comes in two kinds, timezone-aware and naive, and mixing them in arithmetic raises an error immediately. When you are starting out, use naive local time; learn zoneinfo when you genuinely need to handle multiple time zones. For log timestamps and dates in file names, naive time is enough.
Group 5: json — the common language programs use to talk to each other
JSON is the most common format for exchanging data between programs: config files, API responses, small data files saved to disk — most of them are JSON. Python reads and writes it with two functions: dumps turns a Python object into a string, loads turns it back.
import json
data = {"shop": "Morning Light Bookshop", "total": 259.9, "items": ["book", "pen"]}
s = json.dumps(data, ensure_ascii=False)
print(s)
# {"shop": "Morning Light Bookshop", "total": 259.9, "items": ["book", "pen"]}
print(json.loads(s))
# {'shop': 'Morning Light Bookshop', 'total': 259.9, 'items': ['book', 'pen']}
Watch the ensure_ascii=False argument: without it, non-ASCII text is converted to \u escapes. I verified that json.dumps({"café": 1}, ensure_ascii=True) gives {"caf\u00e9": 1} — readable by machines, painful for humans. For config files and logs that people will read, remember ensure_ascii=False.
JSON has two hard rules, and you remember them after tripping over them once. First, keys and strings must use double quotes — single quotes are not allowed:
try:
print(json.loads("{'a': 1}"))
except Exception as e:
print("json single-quote error:", type(e).__name__, e)
# json single-quote error: JSONDecodeError Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
Python accepts both quote styles, but JSON only accepts double quotes. Copying a Python dict and pasting it as JSON is the most common way to fall over here. Second, JSON only recognises a few types: dicts, lists, strings, numbers, booleans and None. Python-specific things like dates and sets cannot be stored directly — convert them to strings or lists first.
When working with files, use json.dump and json.load so you do not go through a string in between. Always pass encoding="utf-8" when saving, or non-ASCII text may get mangled. The two pairs differ by a single letter, so do not mix them up: the ones with an s handle strings, the ones without handle files.
Group 6: re — regular expressions, just enough to be useful
Regular expressions have a bad reputation; many people think they read like gibberish. In daily use you only need a few moves: finding numbers, finding a fixed pattern, replacing text. Here are the three functions you will use most:
import re
text = "Order ORD-2026-1123 Amount 259.9"
print(re.findall(r"\d+", text))
# ['2026', '1123', '259', '9']
print(re.search(r"ORD-\d+-\d+", text).group())
# ORD-2026-1123
print(re.sub(r"\d+\.\d+", "XXX", text))
# Order ORD-2026-1123 Amount XXX
findall returns every match: \d+ means "one or more digits", which is why 259.9 is split into 259 and 9. search finds the first match, and .group() returns the matched text. sub replaces matches, swapping the amount for XXX. These three cover about eighty percent of everyday needs.
The official tutorial gives two classic examples: re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest') returns ['foot', 'fell', 'fastest'], finding every word starting with f; and re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat') merges the doubled "the" into one, giving 'cat in the hat'. You do not need to understand every character — just know that regex can do this kind of work.
Two traps to remember. First, write patterns with an r prefix, like r"\d+" — a raw string — or Python will process the backslashes first and the pattern will not be what you intended. Second, search returns None when nothing matches, and calling .group() on it raises an error:
try:
print(re.search(r"\d+", "abc").group())
except Exception as e:
print("re None error:", type(e).__name__, e)
# re None error: AttributeError 'NoneType' object has no attribute 'group'
The correct pattern is to check first: m = re.search(...); if m: print(m.group()). The tutorial also gives this advice: for simple jobs, do not use regex at all. The string methods replace, split and startswith are easier to read and easier to debug. If a string method can solve it, use the string method.
Group 7: statistics, math, random, heapq — number jobs in one package
This group all deals with numbers, and the split is clear: statistics computes summary figures, math does mathematical operations, random handles randomness, and heapq finds the largest or smallest few.
statistics saves you from writing sum-then-divide yourself:
import statistics
nums = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
print(statistics.mean(nums)) # 1.6071428571428572
print(statistics.median(nums)) # 1.25
This data set is the one from the official tutorial: the mean is about 1.61 and the median is 1.25. There is also variance for variance, stdev for standard deviation, and mode for the most common value. For modest amounts of data, use it directly; reach for a dedicated scientific library only when the data gets large.
math is home base for mathematical functions:
import math
print(round(math.sqrt(2), 4)) # 1.4142
print(math.ceil(2.1)) # 3
print(math.floor(2.9)) # 2
sqrt is the square root, ceil rounds up, floor rounds down. And then there is the classic trap: floating-point arithmetic is not exact.
print(0.1 + 0.2) # 0.30000000000000004
print(0.1 + 0.2 == 0.3) # False
0.1 plus 0.2 is not exactly 0.3 inside a computer. This is an old property of binary floating-point numbers, not a Python bug. When you work with money, do not compare floats for equality: store amounts as integer cents, use the decimal module, or compare approximately, as the pytest guide explained.
random generates random numbers, used in tests, lotteries and shuffling. The key habit is to set a seed first:
import random
random.seed(42)
print(random.choice(["book", "pen", "bag"])) # bag
print(random.sample(range(10), 3)) # [1, 0, 4]
seed(42) fixes the random sequence, so the same code produces the same results every run: choice picks bag, sample picks [1, 0, 4]. Without a seed, every run gives different results and tests cannot be written against them. The number 42 has no special meaning — it is a convention; any fixed number works, as long as you fix one.
heapq is the right tool for "the biggest few" or "the smallest few". To find the top two salespeople by sales, you could sort everything and slice — but heapq is faster when the data is large:
import heapq
scores = [("Ming", 88), ("Hong", 95), ("Gang", 72)]
print(heapq.nlargest(2, scores, key=lambda x: x[1]))
# [('Hong', 95), ('Ming', 88)]
print(heapq.nsmallest(1, [5, 2, 9, 1])) # [1]
nlargest and nsmallest accept a key argument telling them what to compare. With only a few dozen items, the difference from sorted is small; with tens of thousands of items and only the top few wanted, heapq is clearly the better fit.
Group 8: argparse and logging — making a script behave like a proper tool
The earlier groups were about "computing things"; this one is about "turning a program into a tool". A daily-report script cannot have its date hard-coded, can it? argparse handles exactly that: letting a script accept arguments from the command line.
import argparse
p = argparse.ArgumentParser(description="Morning Light Bookshop daily report (fictional data)")
p.add_argument("--day", default="2026-11-23")
p.add_argument("--top", type=int, default=2)
args = p.parse_args()
print(args.day, args.top) # 2026-11-23 2
Run it as python3 report.py --day 2026-11-23 --top 2 and the arguments come in. --top declares type=int, so the incoming string is converted to an integer automatically. Running python3 report.py --help prints usage instructions for free — no separate documentation needed:
usage: report.py [-h] [--day DAY] [--top TOP]
Morning Light Bookshop daily report (fictional data)
options:
-h, --help show this help message and exit
--day DAY
--top TOP
Without it, you would parse sys.argv yourself — working out which token is --day, which is its value, and writing your own error when an argument is missing. Once the arguments grow, that parsing code becomes longer than the actual work. argparse takes care of all of it, and --help comes along for free.
logging records what a program does, and it beats print. print output all looks the same; logging has levels:
import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
logging.info("Open for the day")
# INFO: Open for the day
info is ordinary information, warning is a warning, error means something went wrong. One basicConfig call sets the format and the level. Two rules are enough to start: use info for normal progress and error when something fails, and stop filling the screen with print debugging. When you later want logs written to a file or rotated daily, that is what handlers are for.
Group 9: dataclasses and typing — keeping your data tidy
The namedtuple from group 2 stored a book, and it was light — but it has two limits: fields cannot have defaults, and it cannot have methods. dataclass is its upgrade, and it is almost as simple to write:
from dataclasses import dataclass
from typing import Optional
@dataclass
class Item:
name: str
price: float
qty: int = 1
note: Optional[str] = None
def total(self):
return round(self.price * self.qty, 2)
print(Item("book", 59.9, 2))
# Item(name='book', price=59.9, qty=2, note=None)
print(Item("book", 59.9, 2).total()) # 119.8
The @dataclass decorator writes __init__ and __repr__ for you, so you skip the boilerplate. qty defaults to 1 and note to None, so both are optional. total() is a method you write yourself, computing the line total. When should you switch from namedtuple to dataclass? When you need defaults, methods, or fields that may change.
typing adds type annotations to code. The name: str, price: float and Optional[str] above are annotations: they tell anyone reading the code that this field should be a string, that one a float, and that note may be a string or None. Optional means "may be absent" — it is the same as str | None, and both spellings work in Python 3.10 and later.
Type annotations are never checked at runtime; wrong ones still run. Their real audience is people and tools: editors use them for autocompletion and error hints, and readers can see at a glance what each argument should be. When you start, do not annotate everything — begin with function parameters and return values, and dataclass fields. A wrong annotation is not fatal; a clear one saves a lot of back-and-forth.
Group 10: tempfile, shutil and urllib — file chores and networking
The last group is three "finishing" tools: temporary files, moving files around, and making web requests.
tempfile manages temporary files. Tests, downloads and intermediate results all need a place that gets thrown away afterwards. Hard-coding a path in your code is easy to forget to clean up, and it can collide with someone else's files:
import tempfile, shutil
from pathlib import Path
with tempfile.TemporaryDirectory() as td:
src = Path(td) / "a.txt"
src.write_text("hello", encoding="utf-8")
dst = Path(td) / "b.txt"
shutil.copy(src, dst)
print(dst.read_text(encoding="utf-8")) # hello
When the with block ends, the whole temporary directory and everything in it is deleted — nothing for you to remember. shutil is "high-level file operations": copy copies a file, move moves one, copytree copies a whole directory, rmtree deletes a whole directory. Note that rmtree does not go through a recycle bin — check the path three times before using it.
urllib is the standard library's own networking tool. To fetch a little data from the web, you do not need to install requests first:
from urllib.request import urlopen
with urlopen("https://docs.python.org/3/", timeout=10) as r:
print("urllib status", r.status, "content-type", r.headers.get_content_type())
body = r.read(200)
print("first bytes", body[:60])
# urllib status 200 content-type text/html
# first bytes b'<!DOCTYPE html>\n\n<html lang="en" data-content_root="./">\n <'
I ran this for real and got status 200, with the page's HTML coming back. Note that what you read is bytes, not a string — decode it with .decode("utf-8") before treating it as text, exactly as the official tutorial's example does.
So when is requests still worth it? urllib can do everything, but it is wordy: adding headers, sending JSON, handling errors all take extra lines. requests wraps all of that up, so it reads more smoothly. The rule is: for a quick fetch, or when you do not want another dependency, use urllib; for frequent API calls, complex parameters or long-term maintenance, installing requests pays off. Both work — pick by the situation, not by dogma.
Putting it together: a daily-report script using ten groups
We have toured ten groups; time to assemble them. This report.py is the closing exercise, using only modules from this guide, with fictional data:
"""Bookshop daily report: ties the tour together (fictional data)."""
import argparse, json, logging
from collections import Counter
from dataclasses import dataclass
from datetime import date
from pathlib import Path
import statistics
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
@dataclass
class Sale:
item: str
price: float
qty: int = 1
def total(self): return round(self.price * self.qty, 2)
def main():
p = argparse.ArgumentParser(description="Morning Light Bookshop daily report (fictional data)")
p.add_argument("--day", default="2026-11-23")
p.add_argument("--top", type=int, default=2)
args = p.parse_args()
sales = [Sale("book", 59.9, 2), Sale("pen", 12.5, 3),
Sale("book", 59.9, 1), Sale("bag", 100.0, 1)]
day = date.fromisoformat(args.day)
total = round(sum(s.total() for s in sales), 2)
counts = Counter(s.item for s in sales)
amounts = [s.total() for s in sales]
logging.info("Counting sales for %s", day)
print(f"Date: {day} ({day.strftime('%A')})")
print(f"Total sales: {total} yuan")
print(f"Top {args.top} sellers: {counts.most_common(args.top)}")
print(f"Average per order: {round(statistics.mean(amounts), 2)} yuan")
out = Path(f"report-{args.day}.json")
out.write_text(json.dumps({"day": args.day, "total": total},
ensure_ascii=False), encoding="utf-8")
print(f"Wrote {out}: {out.read_text(encoding='utf-8')}")
out.unlink()
if __name__ == "__main__":
main()
Running python3 report.py --day 2026-11-23 --top 2 for real gives this output:
INFO: Counting sales for 2026-11-23
Date: 2026-11-23 (Monday)
Total sales: 317.2 yuan
Top 2 sellers: [('book', 2), ('pen', 1)]
Average per order: 79.3 yuan
Wrote report-2026-11-23.json: {"day": "2026-11-23", "total": 317.2}
Line by line: argparse takes the arguments, dataclass holds each sale, Counter counts bestsellers, statistics computes the average, datetime handles the date, pathlib plus json writes the report, and logging tracks progress. Eight of the ten groups appear in this one script. Try passing a date that does not exist — --day 2026-13-40 raises ValueError: month must be in 1..12. There is no thirteenth month, and the module stops you right there.
Five common pitfalls, with fixes
- Building paths by gluing strings together. It may break on another system. Fix: join paths with pathlib's slash operator.
- Writing single quotes in JSON. Legal in Python, illegal in JSON — loads raises JSONDecodeError. Fix: always use double quotes in JSON.
- Calling .group() on a re.search that found nothing. A miss returns None, and calling a method on it raises AttributeError. Fix: check that something was found before taking the result.
- Comparing floats with ==.
0.1 + 0.2 == 0.3is False. Fix: store money as integer cents, use decimal, or compare approximately. - Writing everything yourself. Hand-rolled counting loops, hand-computed leap years, hand-parsed sys.argv — longer to write and easier to get wrong. Fix: check the standard library first. Counter, datetime and argparse have probably already done the work for you.
Wrap-up: how to keep exploring
That is the tour. You now have a set of tools for everyday work: paths, counting, looping, dates, data exchange, regular expressions, statistics, command-line arguments, logging, data classes, temporary files and networking. Next time a new problem shows up, ask yourself three questions: is this about paths, about data, or about input and output? Find the group, then look up the exact function in the official docs. That is faster — and steadier — than writing everything from scratch.
Three more names worth knowing, though they did not get a full section: csv for reading and writing spreadsheets, sqlite3 for a small built-in database, and zipfile and tarfile for archives. They work the same way as everything in this guide — learn them from the docs when you need them. The habit that matters is the one to build: before writing code, ask whether the standard library already has someone who wrote it for you. The more you ask, the less you write — and the fewer mistakes you make.
A good next step is the "Brief Tour of the Standard Library" chapter in the official tutorial, or adding an argparse plus logging command-line entry point to one of your own small projects. Pick three groups from this guide, get them running, and the guide will have done its job.
Comments (0)
Sources
Related articles
Adding a book parses to price=59.9, count=3, total 179.7; listing by price takes 2; four errors all exit with code 2; --pri abbreviates, and no subcommand parses to None. Python 3.12.3 stdlib, measured.
Port 8000 in code, 8080 in the config file, 9090 from the environment: each layer changes only its own keys, and the last one wins. Defaults plus INI plus env vars, bool('False') is True, and a missing key should fail at startup. Python 3.12.3 stdlib only.
tmux 3.4, zero packages: 1 session, 2 windows, 3 panes; the logs window prints 1 to 5, editor panes report ready. Detach with Ctrl-b d, reattach with tmux attach — the session outlives the connection. Mouse, prefix key and history limit in ~/.tmux.conf included.