Python JSON and CSV Files: Reading Data and Web APIs

Learn to move real data in and out of Python programs. Build file paths with pathlib, read and write CSV files with the csv module, including files with semicolons, decimal commas and other local formats, and convert data to and from JSON. Then call web APIs over HTTP with the requests library: send parameters and JSON bodies, read status codes and responses, keep API keys out of your code, and handle timeouts, errors, retries and rate limits. The material ends with a small pipeline that fetches API data and saves it as clean, reusable files.

IntermediateLesson 5 of 9 in Intermediate Python Course

What you will learn

  1. Build file paths that work on every operating system, and read, write and organize text files with an explicit encoding.
    • Build and inspect paths with pathlib
      Create paths with Path and the / operator, take them apart into name, stem, suffix and parent, and see how relative paths are resolved.
    • Read, write and organize files and folders
      Check whether files exist, list and create folders, read and write whole text files with the right encoding, and replace files safely.
  2. Turn CSV files into rows and dictionaries, convert their text values, write correctly quoted CSV output, and handle files that use other separators, number formats and date formats.
    • Read CSV files into rows and dictionaries
      Read CSV files with csv.reader and csv.DictReader, convert the text values to numbers, and deal with empty or invalid fields.
    • Write CSV files with csv.writer and csv.DictWriter
      Write lists and dictionaries to CSV with correct quoting and line endings, add a header, and choose between replacing and appending.
    • Handle other separators, encodings and local number and date formats
      Read and write CSV files that use semicolons, tabs, decimal commas, day-first dates or legacy encodings, and convert them to clean values.
  3. Convert between Python objects and JSON text, store data safely in JSON files, and extract the values you need from nested JSON, including dates and times.
    • Convert between Python objects and JSON text
      Know the JSON value types and syntax rules, use json.dumps and json.loads, and predict how Python types change on the way to JSON and back.
    • Read and write JSON files safely
      Load and save JSON files with the right encoding, recognize and locate invalid JSON, and keep settings and data files from being lost or damaged.
    • Navigate nested JSON and handle dates and times
      Extract values from nested API data, handle missing and null fields, flatten records into rows, and parse timestamps into time-zone-aware datetimes.
  4. Explain how HTTP and REST APIs work, call them from Python with the requests library, and authenticate with API keys without exposing them.
    • Understand HTTP requests, responses and REST APIs
      Describe the parts of an HTTP request and response, interpret status codes, and map REST operations to HTTP methods.
    • Call APIs with the requests library
      Send GET and POST requests with parameters, headers and JSON bodies, read the response, and loop through paginated results.
    • Authenticate with API keys and keep secrets out of code
      Send API keys and tokens the way an API expects, load them from the environment, and prevent, detect and repair leaks.
  5. Make API code fail clearly instead of hanging or crashing, retry only the failures worth retrying, and combine files and APIs into a dependable data pipeline.
    • Set timeouts and handle request errors
      Give every request a timeout, turn error status codes into exceptions, and catch the requests exceptions in the right order.
    • Retry failures and respect rate limits
      Tell temporary failures from permanent ones, retry safely with exponential backoff, and stay within an API's rate limits.
    • Build a small, reliable API-to-file pipeline
      Combine configuration, requests, validation, conversion and file output into one program that can be rerun safely and reports what it did.

Python JSON and CSV Files study guide

5 chapters

1

Find, read and write files with pathlib

A script may run from a terminal, an editor or a scheduler, each with a different starting folder. Build paths that still identify the intended input, then choose how to read and write its bytes. You will inspect path parts, create output folders, find groups of files and replace completed output safely. These file operations provide the foundation for the CSV tables, JSON documents and cached API responses that follow.

1.1 Build and inspect paths with pathlib

A path tells Python where to find or save something. A Path object keeps the parts together and provides operations for inspecting them. Constructing one does not create a file or check that it exists.

Build paths from parts
from pathlib import Path

p = Path("data") / "2026" / "sales.csv"

The / operator joins parts with the separator for the current operating system. Path produces a PosixPath on macOS and Linux and a WindowsPath on Windows. Passing p to open() works directly; call str(p) only when another library requires a string.

Keep joined parts relative when you want to stay under a base folder. On macOS or Linux, Path("data") / "/tmp/x.csv" gives /tmp/x.csv: the absolute right-hand part replaces the earlier path.

Inspect and change the name

For p = Path("reports/2026/sales.tar.gz"):

ExpressionResult
p.name"sales.tar.gz"
p.stem"sales.tar"
p.suffix".gz"
p.suffixes[".tar", ".gz"]
p.parentPath("reports/2026")

The stem removes only the last suffix. p.with_suffix(".json") therefore produces reports/2026/sales.tar.json, while p.with_name("costs.csv") replaces the complete name. Both return new paths; p stays unchanged. Path objects are immutable.

Suffixes include the dot and preserve case. To recognize Orders.CSV, compare p.suffix.lower() == ".csv". Comparing with "csv" misses the dot as well as the case.

Choose the starting folder

An absolute path identifies a location from the file-system root. A relative path is interpreted from the current working directory, available as Path.cwd(). That folder depends on where the program starts, not where its script is stored. Path.home() gives the user's home folder; p.resolve() produces an absolute path, resolving symbolic links and .. parts.

Suppose /home/ana/project/report.py opens Path("data/sales.csv"). Starting it from /home/ana/project finds the project's data. Starting it from /home/ana looks for /home/ana/data/sales.csv. To use data next to the script, anchor the path explicitly:

BASE = Path(__file__).resolve().parent
sales = BASE / "data" / "sales.csv"

Here __file__ identifies the script, resolve() makes its location absolute, and parent selects its folder. In an interactive notebook, where __file__ is unavailable, choose the base folder explicitly.

Keep backslashes literal

In an ordinary Python string, \n starts a newline and \t starts a tab. A Windows path written as "C:\new\table" therefore contains unintended control characters. Write r"C:\new\table", use "C:/new/table" on Windows, or build the path from parts.

To calculate paths for another operating system without disk access, use PureWindowsPath or PurePosixPath. For example, PureWindowsPath(r"C:\data\sales.csv").name gives "sales.csv" even on a Mac.

Key Takeaways

  • Build portable paths with Path and /; construction does not create a file.
  • Relative paths start at the working directory; use an explicit base when location must be stable.
  • stem removes the final suffix, and suffix comparisons include the dot.
  • Path-changing methods return new objects.
  • Use raw strings or forward slashes for Windows path literals.

1.2 Read, write and organize files and folders

Reading text involves two choices: which path to open and how to turn its bytes into characters. Organizing output also means creating its folder and choosing whether a failed write can damage an existing file.

Read text with a known encoding
from pathlib import Path

p = Path("notes") / "a.txt"
text = p.read_text(encoding="utf-8")

read_text() returns the whole file as one string. write_text(text, encoding="utf-8") replaces the complete content and returns the number of characters written. read_bytes() and write_bytes() handle binary data without decoding it. For a large text file, keep memory use low by opening it in a with block and looping over its lines.

UTF-8 represents "é" with the two bytes C3 A9. Reading those bytes as cp1252 produces "é". Before Python 3.15, the default text encoding depended on the locale unless UTF-8 mode was enabled. Python 3.15 enables UTF-8 mode by default. An explicit encoding keeps a data exchange script consistent across versions and machines.

A UTF-8 byte order mark, or BOM, appears as the invisible character \ufeff if read with plain UTF-8. A CSV header may then be "\ufeffname", so looking up "name" fails. Use encoding="utf-8-sig" for a UTF-8 file that may have a BOM; it removes the mark if present.

Find inputs and create output folders

exists(), is_file() and is_dir() distinguish a missing path, a file and a folder. A successful check is only a snapshot: the next open can still fail if something changes. For a read, opening directly and catching FileNotFoundError often expresses the intended behavior more clearly.

iterdir() yields a folder's entries. glob("*.txt") matches entries in that folder; rglob("*.txt") also searches subfolders. Results are Path objects with no guaranteed order. Sort them when order matters, and use is_file() when a pattern could also match a directory.

src = Path("notes")
lines = []
for p in sorted(src.glob("*.txt")):
    if p.is_file():
        count = len(p.read_text(encoding="utf-8").splitlines())
        lines.append(f"{p.name}: {count}")

out = Path("out") / "summary.txt"
out.parent.mkdir(parents=True, exist_ok=True)
text = "\n".join(lines) + "\n"

With 3 lines in a.txt and 12 in b.txt, the text contains "a.txt: 3" followed by "b.txt: 12". parents=True creates missing ancestors. exist_ok=True accepts an existing directory; it does not accept an ordinary file in its place.

Publish a completed file

Opening with "w" empties a file immediately. Write a replacement beside the destination, close it, then replace the destination:

tmp = out.with_name(out.name + ".tmp")
tmp.write_text(text, encoding="utf-8")
tmp.replace(out)

On macOS and Linux, replacement within the same file system is atomic: readers see the old complete file or the new complete file. Encoding or writing failures before replacement leave the old destination in place. Atomic replacement does not guarantee recovery from every disk or power failure.

For deliberate removal, unlink() deletes a file; missing_ok=True accepts an already missing file. rmdir() removes an empty folder. replace(target) overwrites an existing file target across platforms, while rename(target) raises on Windows if that target exists.

Key Takeaways

  • Choose the encoding explicitly; utf-8-sig removes a UTF-8 BOM.
  • Use line iteration when loading the whole text would use too much memory.
  • Sort directory matches when processing order matters.
  • Create output parents with mkdir(parents=True, exist_ok=True).
  • Write and close a temporary file before replacing valuable output.
  • Use unlink() for files and rmdir() for empty folders.
2

Read and write CSV data with the csv module

CSV connects Python scripts with spreadsheets and other programs that exchange tables. Real tables include quoted names, empty fields and values written using different local conventions. You will read records with the CSV parser, convert and validate their text, and write columns in a deliberate order. You will also distinguish a broken delimiter setting from a number, date or encoding problem so that a readable table contains the intended values.

2.1 Read CSV files into rows and dictionaries

CSV is a text table, but a comma does not always end a field. A quoted customer name such as "Lee, Ana" contains a comma that belongs to the name. The csv module reads these rules and leaves type conversion to your program.

Read records, not split lines
import csv
from pathlib import Path

path = Path("orders.csv")
with path.open(newline="", encoding="utf-8") as f:
    reader = csv.reader(f)
    header = next(reader, None)
    for row in reader:
        print(row)

Each row is a list of strings. For 1001,"Lee, Ana",3,4.50, it has four fields. Calling split(",") would produce five pieces because it also splits the customer's name. Quoted fields can contain line breaks, so a record can span several physical lines. Within a quoted field, a double quote is represented by two double quotes.

newline="" lets the CSV parser handle line endings, including those inside fields. Keep iteration inside the with block because the reader needs the open file. A reader is an iterator: once consumed, it does not restart. list(reader) collects the remaining records in memory; a loop can process a file one record at a time.

Use column names

csv.DictReader(f) takes its keys from the header, so row["quantity"] still selects the correct column after columns are reordered. reader.fieldnames exposes those names. If you supply fieldnames yourself, the first record becomes data instead of a header.

Check row shape when input may be damaged. With default settings, a short row gets None for absent fields, and extra fields collect under the key None. A present but empty field is "". DictReader skips blank lines; csv.reader returns [] for them. Spaces can also matter: use skipinitialspace=True for spaces after delimiters or strip selected values before comparing them.

Convert values and report bad rows

Suppose the file contains:

order_id,customer,quantity,unit_price
1001,"Lee, Ana",3,4.50
1002,Omar Haddad,2,12.25
1003,"Kim, Ji-woo",5,

The first two orders contribute 13.50 and 24.50. The last price is missing; treating it as zero would hide incomplete data. This version skips and reports missing or invalid rows, and uses Decimal for exact decimal amounts:

from decimal import Decimal, InvalidOperation

total = Decimal("0")
with path.open(newline="", encoding="utf-8") as f:
    reader = csv.DictReader(f)
    for row in reader:
        if None in row or any(v is None for v in row.values()):
            print(f"Skipped source line {reader.line_num}: wrong field count")
            continue
        if not row["unit_price"].strip():
            print(f"Skipped {row['order_id']}: missing price")
            continue
        try:
            quantity = int(row["quantity"])
            price = Decimal(row["unit_price"])
            if not price.is_finite():
                raise ValueError("price must be finite")
        except (ValueError, InvalidOperation):
            print(f"Skipped {row['order_id']}: invalid quantity or price")
            continue
        total += quantity * price
print(f"{total:.2f}")

The total is 38.00. reader.line_num counts source lines read, which may exceed the record count because of multiline fields. Required header names should be checked before the loop when the source is unfamiliar.

Strings do not behave like numbers: "3" * 2 gives "33". Convert with int, float, or Decimal as the data requires. Construct a Decimal from the original text to avoid introducing a float approximation first.

Key Takeaways

  • Let csv handle quoting and multiline records.
  • Open CSV text with newline="" and an explicit encoding.
  • DictReader uses the header; normal reader values remain strings.
  • Check absent, empty and surplus fields before conversion.
  • Choose a clear invalid-row policy and report skipped data.
  • Use Decimal from text when exact decimal arithmetic matters.
  • Iterate to keep memory use low; collect a list only when needed.

2.2 Write CSV files with csv.writer and csv.DictWriter

A CSV writer handles delimiters and quotes for you. Your choices are the column layout, value formatting and whether each run replaces the table or adds records to it.

Write rows with the right line endings
import csv
from pathlib import Path

path = Path("readings.csv")
with path.open("w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(["city", "temp_c"])
    writer.writerows([["Oslo", -3.5], ["Lima", 20]])

writerow() writes one record; writerows() writes an iterable of records. The default excel dialect ends records with \r\n. Without newline="", Windows can translate the newline again, producing \r\r\n and apparent blank rows.

The default QUOTE_MINIMAL setting quotes fields containing a delimiter, quote or line break and doubles embedded quotes. A value "Lee, Ana" occupies one field even though it contains a comma. An f-string or ",".join(...) does not provide that protection.

Values normally become text through str(); None becomes an empty field. That loses the difference between a missing value and an empty string. A later read normally gives strings again, including strings that look like numbers.

Fix column order explicitly
readings = {"Oslo": [-3.5, -1.0, 0.5], "Lima": [19, 21, 20]}
with path.open("w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=["city", "mean_temp_c"])
    writer.writeheader()
    for city, values in readings.items():
        mean = sum(values) / len(values)
        writer.writerow({"mean_temp_c": f"{mean:.2f}", "city": city})

fieldnames is required and determines output order, regardless of each dictionary's insertion order. Oslo's total is -4.0 across three readings, giving about -1.3333; formatting the final mean produces -1.33. Lima's mean is 20.00 in the output.

A missing dictionary key becomes the default empty restval. An extra key raises ValueError, which can reveal a mismatch between your data and columns. Set extrasaction="ignore" only when dropping those extra values is intentional.

Replace or append
ModeEffectHeader handling
"w"Starts a replacement tableWrite one header at the start
"a"Adds to the existing fileWrite a header only for a new or empty file

For an append script, calculate new_file = not path.exists() or path.stat().st_size == 0, then open with "a". Call writeheader() only when new_file is true. This prevents repeated header records, but does not prevent duplicate data on reruns.

Match the receiving program

Use consistent decimal points, ISO dates and UTF-8 for data exchange. QUOTE_NONNUMERIC is a different contract: its writer quotes nonnumeric fields, and its reader converts unquoted fields to floats. Do not assume a normal reader performs that conversion.

A spreadsheet may display 007 as 7 or reinterpret text as dates. Inspect the original file in a text editor to distinguish stored text from display changes. For untrusted text destined for a spreadsheet, apply that application's CSV-injection protection to fields that could be interpreted as formulas, including those beginning with =, +, - or @; quoting alone does not neutralize a formula.

Key Takeaways

  • Writers handle quoting; newline="" prevents extra newline translation.
  • DictWriter.fieldnames controls the column order.
  • Format values before writing when a fixed number of decimals is needed.
  • Appending needs a header check and a separate plan for duplicate records.

2.3 Handle other separators, encodings and local number and date formats

A CSV source has several independent conventions: its delimiter, encoding, number format and date format. Setting the delimiter fixes the table structure. It does not convert its values into numbers or dates.

Read the source's dialect

A dialect groups CSV formatting rules. The default excel dialect uses commas, double quotes and \r\n record endings. For semicolons, pass delimiter=";"; for tabs, pass delimiter="\t" or dialect="excel-tab".

Consider this export:

product;price;date
Coffee;1.234,56;03.02.2026
Tea;7,90;15.02.2026

With a comma delimiter, the header remains one field, but the data splits at decimal commas. delimiter=";" gives three fields per record. The price is still the string "1.234,56".

When the format is unknown, csv.Sniffer().sniff(sample) can suggest a dialect:

with path.open(newline="", encoding="utf-8") as f:
    sample = f.read(1024)
    dialect = csv.Sniffer().sniff(sample)
    f.seek(0)
    rows = list(csv.reader(f, dialect))

seek(0) returns to the start after sampling. has_header(sample) can suggest whether a header exists. Both operations are guesses and can fail or misidentify unusual data. A documented format is stronger evidence than a short sample.

Convert numbers in the right order

Here a period groups thousands and a comma marks decimals. Remove the grouping mark first, then change the decimal mark:

text = "1.234,56"
price = float(text.replace(".", "").replace(",", "."))

The intermediate strings are "1234,56" and "1234.56", giving 1234.56. Tea's price becomes 7.9; together they total 1242.46. For exact decimal amounts, apply the same text cleanup before constructing Decimal.

The conversion belongs to the source format, not to individual values. "1.234" can mean one thousand two hundred thirty-four or a little over one. Guessing from each value cannot resolve that ambiguity. A source with "1,234.56" needs the opposite treatment: remove commas and keep the decimal point.

Parse dates and decode bytes
from datetime import datetime

d = datetime.strptime("03.02.2026", "%d.%m.%Y").date()
print(d.isoformat())  # 2026-02-03

%d, %m and %Y mean day, month and four-digit year. In month-first notation, "03/02/2026" means March 2; a day-first source means February 3. Parse the documented convention, then write ISO dates to remove the ambiguity.

Encoding is a separate issue. A legacy cp1252 file may contain a single E9 byte for "é", which is not valid UTF-8 by itself. Open it with its documented encoding. errors="replace" substitutes unreadable bytes; it can help inspection but discards information during conversion. Use utf-8-sig for UTF-8 that may begin with a BOM.

When local output is required, write it explicitly with a semicolon writer and f"{value:.2f}".replace(".", ","). For program exchange, document delimiter, decimal mark, dates, encoding and units together, so the next reader can reconstruct the values.

Key Takeaways

  • A dialect controls CSV structure; number and date conversion are separate.
  • Choose decimal and thousands rules per source, before converting values.
  • Rewind after sampling with Sniffer, and verify its guesses.
  • Parse dates with an explicit format and write ISO dates.
  • Decode with the source encoding; replacement characters lose information.
3

Serialize and parse JSON data

JSON represents structured data without flattening every value into a table. It is useful for settings, saved responses and information containing lists inside objects. You will move between JSON text and Python values, protect existing files during saving, and trace nested fields. Dates and times need their own interpretation: the final part shows how to preserve offsets, compare moments and prepare rows from a nested response.

3.1 Convert between Python objects and JSON text

JSON stores structured values as text. A Python dictionary is an in-memory object; printing it does not make JSON. Serialization produces valid JSON text that another program can parse.

Use JSON syntax and the four functions

JSON strings and object keys use double quotes. Boolean values are true and false, and the empty value is null. Comments, single-quoted strings and trailing commas are invalid. Its values are objects, arrays, strings, numbers, booleans and null, nested as needed.

FunctionDirection
json.dumps(obj)Python value to JSON string
json.loads(text)JSON string to Python value
json.dump(obj, f)Python value to an open file
json.load(f)Open file to Python value

The s means string. A string returned by dumps() can be sent, stored or parsed with loads().

Predict type changes
import json

original = {"name": "Zoë", "tags": ("a", "b"), 1: None, "ok": True}
text = json.dumps(original, ensure_ascii=False)
restored = json.loads(text)

The JSON is {"name": "Zoë", "tags": ["a", "b"], "1": null, "ok": true}. A dictionary becomes an object; lists and tuples become arrays. Arrays parse as lists, so the tuple does not return. Object keys are strings, so the integer key becomes "1". None, True and False map to null, true and false and return to their Python equivalents.

Integer-shaped JSON numbers normally parse as int; numbers with a fraction or exponent normally parse as float. JSON has no distinct tuple, set, date or decimal-money type. A round trip can therefore preserve the data's meaning while changing its Python types.

Decide how unsupported values travel

A set, datetime, Decimal or custom instance raises TypeError during encoding unless you convert it. A set can become a sorted list when its items can be sorted; a datetime can become an ISO string; a Decimal can become text to preserve its digits.

from datetime import datetime

def encode_extra(value):
    if isinstance(value, datetime):
        return value.isoformat()
    raise TypeError(f"Cannot encode {type(value).__name__}")

text = json.dumps({"created": datetime(2026, 11, 3)}, default=encode_extra)

The default hook runs only for values the encoder cannot handle. It must return an encodable value or raise TypeError. default=str makes unknown values into strings, but hides their original types. A reader needs a clear convention if those types must be reconstructed.

Control readability and strictness

indent=2 formats nested content for people; sort_keys=True sorts object keys. ensure_ascii=False leaves characters such as "ë" visible instead of writing a Unicode escape. separators=(",", ":") removes optional spacing for compact transport.

Python's default encoder permits NaN and Infinity, although standard JSON does not. Pass allow_nan=False to reject them with ValueError. Duplicate JSON keys also need attention: json.loads('{"x": 1, "x": 2}') keeps only {'x': 2}. For exact decimal parsing, json.loads(text, parse_float=Decimal) builds Decimal values from fractional JSON numbers.

Key Takeaways

  • JSON syntax differs from Python literals; use the JSON encoder.
  • dumps and loads work with strings; dump and load work with files.
  • Tuples return as lists and numeric object keys return as strings.
  • Convert unsupported types deliberately or provide a focused default hook.
  • Use allow_nan=False for standard JSON output.
  • Use parse_float=Decimal when fractional values must stay exact.

3.2 Read and write JSON files safely

A JSON file should contain one complete JSON value. Reading it successfully proves that the syntax is valid; the program still needs to check whether the value has the shape it expects.

Load an open file or parse its text
import json
from pathlib import Path

path = Path("settings.json")
with path.open(encoding="utf-8") as f:
    settings = json.load(f)

json.load() needs a file object with a read() method. Passing "settings.json" supplies a string, not a file. json.loads("settings.json") also fails, because it tries to parse the file name as JSON text. With pathlib, json.loads(path.read_text(encoding="utf-8")) reads and parses in two explicit operations.

Check the result before using it. A document can be a list, object, string, number, boolean or null at its top level. A settings program expecting an object should reject a list even though the list is valid JSON.

Distinguish missing settings from damaged settings
DEFAULTS = {"units": "metric", "page_size": 50}

def load_settings(path):
    try:
        text = path.read_text(encoding="utf-8")
    except FileNotFoundError:
        return dict(DEFAULTS)
    try:
        user = json.loads(text)
    except json.JSONDecodeError as e:
        raise ValueError(
            f"Invalid settings at line {e.lineno}, column {e.colno}"
        ) from e
    if not isinstance(user, dict):
        raise ValueError("Settings must be an object")
    return {**DEFAULTS, **user}

A missing file returns a fresh defaults dictionary. With {"page_size": 100}, the result keeps "units": "metric" and uses the user's page size. A malformed file stops with a location, leaving its content available for repair. The object check prevents a valid but unsuitable JSON value from reaching the merge. Individual settings also need validation before use.

JSONDecodeError is a ValueError subclass. Its lineno, colno, pos and msg help locate invalid syntax. Exact messages and positions can change between Python versions, so catch the exception type instead of comparing message text.

Save without destroying the previous version

json.dump(data, f) encodes incrementally. If an unsupported set appears deep inside the data, opening the destination with "w" has already erased its previous content, and the partial JSON is left behind. First encode everything, then write a temporary file beside the destination:

def save_json(path, data):
    text = json.dumps(data, indent=2, ensure_ascii=False, allow_nan=False)
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_name(path.name + ".tmp")
    tmp.write_text(text, encoding="utf-8")
    tmp.replace(path)

An encoding failure occurs before any write. A temporary-write failure happens before replacement. The fixed temporary name suits one writer at a time; simultaneous writers need separate temporary names.

Choose one document or JSON Lines

Appending two json.dump() calls to a normal JSON file creates adjacent values, not one valid document. JSON Lines instead stores one complete value per line. Read it with a line loop and json.loads(line), and append a compact encoded value followed by "\n". Do not pretty-print each record across several lines.

Use CSV for a flat table with stable columns. JSON handles nesting and retains booleans, numbers and null. Neither has a native date type; use an agreed text format such as ISO 8601.

Key Takeaways

  • Check the loaded value’s shape as well as its JSON syntax.
  • Missing settings can use defaults; damaged settings should produce a clear error.
  • Encode first, then write and close a temporary file before replacement.
  • JSON Lines needs one complete value per line and a per-line parser.

3.3 Navigate nested JSON and handle dates and times

Nested JSON becomes nested dictionaries and lists after parsing. Follow each level's type before extracting values, then turn the fields you need into a flat row. Dates and times need an additional conversion because JSON stores them as text or numbers.

Trace the structure and optional fields
{"city": "Lisbon", "forecast": [
  {"time": "2026-11-03T12:00:00Z", "temp_c": 18.5, "wind": {"speed_kmh": 14}},
  {"time": "2026-11-03T15:00:00Z", "temp_c": 19.0, "wind": null}
]}

data["forecast"][0]["wind"]["speed_kmh"] selects the forecast list, its first item, the wind object and its speed, giving 14. A missing key raises KeyError; an unavailable list index raises IndexError. The second wind value is None, so subscripting it raises TypeError.

item.get("wind", {}) handles an absent key, but returns None for an explicit null. Once you have checked that wind is an object or null, (item.get("wind") or {}).get("speed_kmh") handles both absence and null. It is not a substitute for validating other unexpected types.

Inspect unfamiliar responses with type(data), dictionary keys(), list len() and a small pretty-printed excerpt. Required values should have clear checks. isinstance(value, (int, float)) accepts True, because bool subclasses int; reject booleans separately for measurements.

Flatten records into rows
rows = []
for item in data["forecast"]:
    wind = item.get("wind")
    rows.append({
        "city": data["city"],
        "time": item["time"],
        "temp_c": item["temp_c"],
        "wind_speed_kmh": (wind or {}).get("speed_kmh"),
    })

This creates two rows, keeping the city beside each reading. The second wind speed is None, which a CSV writer turns into an empty field. Validate the outer object, list, records and required fields before this transformation so failures name the actual problem.

Parse moments with their offsets
from datetime import datetime, timezone
from zoneinfo import ZoneInfo

text = "2026-11-03T14:00:00Z"
t = datetime.fromisoformat(text.replace("Z", "+00:00"))
utc = t.astimezone(timezone.utc)
print(utc.isoformat())  # 2026-11-03T14:00:00+00:00

Z means UTC. Python 3.11 and later parse it directly; replacing it as shown also supports Python 3.10. A datetime with a usable UTC offset is aware; without one it is naive. Reject a missing offset when a field promises an unambiguous moment. Work in UTC with datetime.now(timezone.utc); the deprecated utcnow() produces a naive datetime.

Ordering a naive and an aware datetime raises TypeError, while equality returns False. Removing time-zone information to silence the error loses the information needed to compare moments.

Unix timestamps normally count seconds since 1970-01-01 00:00 UTC. datetime.fromtimestamp(1700000000, tz=timezone.utc) gives 2023-11-14 22:13:20 UTC. Divide millisecond timestamps by 1000 first.

For display, utc.astimezone(ZoneInfo("Asia/Tokyo")) gives 23:00 on November 3. Named zones apply daylight-saving rules: in Amsterdam, 00:30 UTC on March 29, 2026 is 01:30 local, while 01:30 UTC is 03:30 local. On Windows, install the tzdata package to supply the zone database.

Key Takeaways

  • Trace dictionary keys and list indexes one level at a time.
  • A default in .get() does not replace an explicit null.
  • Validate types before flattening, including rejecting boolean measurements.
  • Keep an offset when parsing moments, then normalize to UTC.
  • Check whether Unix timestamps use seconds or milliseconds.
  • Use named time zones for display with daylight-saving rules.
4

Request data from web APIs

Calling a web API joins two separate tasks: describing an HTTP request and interpreting what comes back. You will read methods, status codes and headers, then use requests to send parameters, JSON bodies and credentials. Collections may require several pages, and credentials need a secure place outside the program. Understanding these contracts makes later error handling more precise because each failure can be tied to a specific part of the exchange.

4.1 Understand HTTP requests, responses and REST APIs

A web API lets a program ask a remote service for data or changes. The client sends an HTTP request and the server sends a response. HTTPS protects that exchange with TLS encryption.

Identify the request and response parts

In https://api.example.com/v1/cities/lisbon/forecast?days=3&units=metric, https is the scheme, api.example.com is the host, /v1/cities/lisbon/forecast is the path, and the text after ? is the query string. Its parameters are separated by &.

A request has a method, URL, headers and sometimes a body. Accept: application/json asks for JSON; Authorization carries credentials. Header names ignore case. A response has a status code, headers and a body. Its Content-Type describes the returned representation.

Read the status before using the body
CodesMeaning
1xxInformational
2xxSuccess
3xxRedirection or cache-related response
4xxA client-side request problem
5xxA server-side failure

200 means OK; 201 means one or more resources were created; 204 means success with no content. Redirects such as 301 and 302 normally lead the client to another URL. 304 tells a conditional request to use its existing cached representation.

For request problems, distinguish 400 malformed request, 401 missing or invalid credentials, 403 refusal to carry out the action, 404 missing resource, 422 well-formed but invalid data, and 429 exceeded rate limit. A 403 does not prove the caller was authenticated. Common server failures include 500 internal error, 502 bad gateway, 503 unavailable service and 504 gateway timeout. Read the documented error body to decide what needs changing or whether a later retry makes sense.

Match methods to resource operations

A typical REST API gives a collection the path /books and a particular book /books/42. REST is an API design style; stateless requests carry the information needed to process each call, including credentials.

RequestTypical purpose
GET /booksList books
GET /books/42Read one book
POST /booksCreate a book
PUT /books/42Replace a book
PATCH /books/42Change selected fields
DELETE /books/42Remove a book

Safe methods such as GET, HEAD and OPTIONS are intended to read without requesting a state change. Idempotent methods have the same intended effect when an identical request is repeated. GET, HEAD, OPTIONS, PUT and DELETE are idempotent; POST and PATCH are not guaranteed to be.

The response need not repeat. A first DELETE may return 204 and a second 404, while both leave the book absent. Two identical POST requests may create two books, which matters when a response is lost.

Follow the API's collection rules

Read the documentation for base URL, version, parameters, units, authentication, rate limits and error format. Pagination may use page numbers, offset and limit, or a cursor/next link. With 230 items and pages of 50, four full pages contain 200 and the fifth contains 30. Stop using the API's documented rule: a short or empty page, or the absence of a next link. These rules are not interchangeable.

Key Takeaways

  • Requests have a method, URL, headers and optional body; responses add a status.
  • Interpret status codes before treating the body as usable data.
  • REST methods express operations on resources.
  • Idempotency concerns repeated effects, not identical response codes.
  • Use the documented pagination and stopping rule.

4.2 Call APIs with the requests library

The third-party requests library handles HTTP details while your code chooses the endpoint, parameters and expected response. Install it in the project's virtual environment with python -m pip install requests. Python's standard-library alternative is urllib.request.

Send parameters and inspect the result

The example.com URLs below illustrate API contracts. Substitute a provider's documented endpoint when making a real request.

import requests

url = "https://api.example.com/v1/search"
r = requests.get(url, params={"q": "café latte", "page": 2}, timeout=10)
r.raise_for_status()
data = r.json()

params constructs a query string and encodes special characters. The search value becomes caf%C3%A9+latte; a value of None omits that parameter. Hand-built URLs can mistake a value's & for a parameter separator. r.url shows the final URL.

Attribute or methodResult
r.status_codeInteger status code
r.headersCase-insensitive response headers
r.textDecoded body text
r.contentRaw body bytes
r.json()Parsed JSON value

r.ok accepts statuses below 400; it is not a guarantee of the success response your program expects. A 404 body can be valid JSON. Check status with raise_for_status() before parsing, then validate the shape. Skip JSON parsing for an expected 204 response, whose body is empty.

Send a JSON body
payload = {"title": "Dune", "year": 1965}
r = requests.post(
    "https://api.example.com/v1/books",
    json=payload,
    timeout=10,
)
r.raise_for_status()
created = r.json()

json=payload serializes the body and sets Content-Type: application/json. data=payload sends a dictionary as form data with a different content type. Choosing the wrong one can produce a 400 or 415 error. PUT, PATCH and DELETE have corresponding functions.

Add request headers with headers={"Accept": "application/json"}. Some providers require a User-Agent naming the application and a contact address; follow their instructions.

Reuse a session and collect pages

A Session reuses connections and shared settings. A header on one call overrides a session header of the same name for that call. Use a session inside a with block so it closes after use.

def fetch_all(session, url):
    items = []
    for page in range(1, 101):
        r = session.get(
            url, params={"page": page, "per_page": 50}, timeout=10
        )
        r.raise_for_status()
        batch = r.json()["items"]
        if not isinstance(batch, list):
            raise ValueError("Expected an items list")
        items.extend(batch)
        if len(batch) < 50:
            return items
    raise RuntimeError("Page limit reached; results may be incomplete")

with requests.Session() as session:
    session.headers.update({"Accept": "application/json"})
    items = fetch_all(session, "https://api.example.com/v1/books")

This API stops on a short page. With 230 items it takes five requests. With exactly 200, page five is empty and confirms completion. Reaching the guard raises instead of returning partial results as complete. An API using next links needs that different stopping rule; requests exposes parsed Link headers through r.links.

Save a development response locally for inspection and respect the provider's rate limits, so exploring its structure does not use a new request every time.

Key Takeaways

  • Use params for query strings and json for a JSON request body.
  • Check status, parse the expected body, then validate its structure.
  • r.text, r.content and r.json() expose different representations.
  • Sessions reuse connections and shared headers.
  • Pagination must advance and stop according to the API contract.
  • A page-limit guard must report incomplete results instead of silently returning them.

4.3 Authenticate with API keys and keep secrets out of code

A secret API key gives its holder access to an account or application. Good handling starts with sending it in the documented place and keeping it separate from code that will be copied or shared.

Separate identity from permissions

Authentication establishes who is calling; authorization decides what the caller can do. A key or token may identify a project, account or application. Tokens often expire. Someone holding your credential may read private data, consume quota or create charges within its permissions.

Read the API's authentication instructions. Common forms are Authorization: Bearer <token>, X-API-Key: <key>, or a query parameter. Prefer a header when supported because URLs often appear in logs, browser history and error messages. Header credentials still need protection in debugging output.

import os
import requests

key = os.getenv("WEATHER_API_KEY")
if not key:
    raise SystemExit("Set the WEATHER_API_KEY environment variable first.")

with requests.Session() as session:
    session.headers.update({"Authorization": f"Bearer {key}"})
    r = session.get("https://api.example.com/v1/forecast", timeout=10)
    r.raise_for_status()

The environment variable is configured outside the program. os.getenv() returns None when it is absent; direct access with os.environ["WEATHER_API_KEY"] raises KeyError. Check configuration at startup so the program does not send a malformed Bearer None header.

For an API using HTTP Basic authentication, requests accepts auth=(username, password). Use only the method that API documents; changing the header's name does not change the server's contract.

Keep local settings out of source control

A .env file can hold local environment settings. The optional python-dotenv package loads them with from dotenv import load_dotenv and load_dotenv(). Python does not load .env automatically.

Add .env to .gitignore before committing it. A shareable .env.example can list variable names with placeholders. Never put a working credential in that example. Deleting a key in a later commit leaves earlier copies in repository history, so prevention and revocation matter more than deleting the latest line.

Control exposure and recover from leaks

Do not print keys, complete authorization headers or URLs containing keys. A traceback may include the request URL. Share diagnostic status codes and safe context instead of entire request objects. A short masked prefix can identify a key without displaying it in full.

If a credential leaks, revoke or rotate it through the provider immediately and update the environment. Removing it from code does not invalidate copies already made. Use a separate key per project and environment, with only the permissions required. A read-only reporting program should have a read-only key where available.

HTTPS encrypts the exchange, and requests verifies the server's TLS certificate by default. Keep verification enabled: disabling it can let a network attacker impersonate the server. Repair the certificate or trusted-certificate configuration when verification fails.

An environment variable separates a secret from source code; it does not make a secret safe on someone else's device. A key shipped inside browser JavaScript or a distributed desktop application can be extracted. Shared service credentials belong on machines you control.

Key Takeaways

  • Use the API’s documented authentication method, preferably a header when supported.
  • Load secrets from the environment and check for missing values at startup.
  • Keep local secret files and diagnostic output from exposing credentials.
  • Revoke leaked credentials and grant each project only needed permissions.
  • Keep TLS verification enabled and shared secrets on controlled machines.
5

Handle timeouts, errors and unreliable services

Network services and local files can fail independently of correct Python syntax. A request may stall, a service may ask you to wait, or a write may stop before the file is complete. You will bound waits, classify failures and retry only safe operations. The final pipeline brings those decisions together with validation, caching and completed-file replacement, so a repeatable export either publishes usable data or reports a clear failure.

5.1 Set timeouts and handle request errors

A request can fail before a server responds, return an error status, or return a body your program cannot use. Locate the failure stage so the program can report it clearly and choose an appropriate response.

Bound network waits

requests has no default timeout. Pass one on every call. timeout=10 sets both connection and read timeouts; timeout=(3.05, 10) sets them separately. The connection limit bounds establishing the connection. The read limit bounds waiting for incoming data, not the entire download. A server that keeps sending small amounts can take longer than ten seconds overall.

A server that accepts a connection but sends no response headers in time normally produces ReadTimeout. A stall while downloading a response body can surface as requests.exceptions.ConnectionError. Catch both relevant families when planning recovery.

Check status and then parse
r = session.get(url, timeout=(3.05, 10))
r.raise_for_status()
data = r.json()

A normal get() returns a Response even for 404 or 500. raise_for_status() turns 4xx and 5xx statuses into HTTPError. Parsing the body is another operation: an HTML maintenance page with status 200 causes r.json() to raise requests.exceptions.JSONDecodeError.

Valid JSON can still lack required fields. That is a data-validation problem in your program, not proof of a network failure. Check required keys and types before processing records.

Catch specific exceptions first

All requests exceptions derive from requests.exceptions.RequestException. Important branches include Timeout, ConnectionError, HTTPError, TooManyRedirects and JSONDecodeError. Use their qualified names: the built-in ConnectionError is a different class.

import requests

def fetch_json(session, url):
    try:
        r = session.get(url, timeout=(3.05, 10))
        r.raise_for_status()
        return r.json()
    except requests.exceptions.Timeout as e:
        raise RuntimeError("The request timed out") from e
    except requests.exceptions.HTTPError as e:
        raise RuntimeError(f"API returned status {e.response.status_code}") from e
    except requests.exceptions.JSONDecodeError as e:
        raise RuntimeError("API response was not valid JSON") from e
    except requests.exceptions.ConnectionError as e:
        raise RuntimeError("Could not complete the connection") from e
    except requests.exceptions.RequestException as e:
        raise RuntimeError("The request failed") from e

Python takes the first matching handler. The general handler belongs last. ConnectTimeout inherits from both Timeout and requests' ConnectionError; putting the Timeout handler first preserves the timeout-specific message. raise ... from e keeps the original cause for debugging. Keep any chained traceback containing sensitive request details out of shared logs.

For an HTTP error, e.response.status_code identifies the status and e.response.text may explain the request problem. Inspect only what is safe and useful, since responses can contain private information.

Give failure a useful outcome

Handle an exception where you can retry, use a justified default, or skip and report a bad record. Otherwise let it propagate with clear context. except Exception: pass and unexplained None returns hide the original failure and often produce a confusing error later. A failed fetch must not quietly turn into a successful empty export.

Key Takeaways

  • Every request needs a timeout; a read timeout is not a total deadline.
  • Call raise_for_status() because error statuses do not raise automatically.
  • Separate connection, status, JSON-syntax and data-shape failures.
  • Put specific requests exception handlers before general ones.
  • Report a useful failure instead of swallowing it.

5.2 Retry failures and respect rate limits

Retries are useful when another attempt can succeed and repeating the request is safe. They need limits and waiting time so a busy service does not receive an immediate burst of repeated calls.

Decide whether to repeat

Connection failures, timeouts and statuses 429, 502, 503 and 504 are common retry candidates. A 500 may justify a small number of retries. A malformed request, invalid credentials, forbidden action, missing resource or invalid submitted value normally needs a change, so do not repeatedly send an unchanged 400, 401, 403, 404 or 422 request.

Restrict automatic retries to idempotent operations such as GET. If a POST created an order but its response was lost, another POST can create a duplicate. A provider's documented idempotency-key mechanism can make that repeated creation request safe; do not assume it exists.

Increase waits and obey the server

With base 1 second and factor 2, four retry waits are 1, 2, 4 and 8 seconds. That is five attempts and 15 seconds of waiting. Cap your own exponential delay and the total attempt count. Add small random jitter so clients that failed together do not all retry together.

Retry-After can contain delay-seconds or an HTTP date. Its valid server-directed wait takes priority over a shorter local backoff. A date in the past gives a zero remaining delay. If a required wait is too long for the job, stop or defer the job; do not shorten it and retry early.

import email.utils
from datetime import datetime, timezone

def server_delay(value):
    value = value.strip()
    if value.isdigit():
        return float(value)
    try:
        when = email.utils.parsedate_to_datetime(value)
    except (TypeError, ValueError, OverflowError):
        return None
    if when.tzinfo is None:
        when = when.replace(tzinfo=timezone.utc)
    return max(0.0, (when - datetime.now(timezone.utc)).total_seconds())
Bound a GET retry loop
import random
import time
import requests

RETRYABLE = {429, 502, 503, 504}

def get_with_retries(session, url, attempts=5):
    if attempts < 1:
        raise ValueError("attempts must be positive")
    for attempt in range(1, attempts + 1):
        backoff = min(30.0, 2.0 ** (attempt - 1))
        try:
            r = session.get(url, timeout=(3.05, 10))
        except (requests.exceptions.ConnectionError, requests.exceptions.Timeout):
            if attempt == attempts:
                raise
            wait = backoff
        else:
            if r.status_code not in RETRYABLE or attempt == attempts:
                r.raise_for_status()
                return r
            delay = server_delay(r.headers.get("Retry-After", ""))
            wait = backoff if delay is None else delay
        print(f"Retry after attempt {attempt}; waiting {wait:.1f} s plus jitter")
        time.sleep(wait + random.uniform(0, 0.5))

Four 503s and then success use the four growing waits. A 404 raises immediately. A 429 with Retry-After: 120 waits at least 120 seconds. The last failed attempt raises without another sleep.

A session can instead mount HTTPAdapter(max_retries=Retry(total=3, backoff_factor=0.5, status_forcelist=[429, 502, 503, 504])), importing HTTPAdapter from requests.adapters and Retry from urllib3.util. Its default allowed methods exclude POST and PATCH; exhausted status retries raise requests.exceptions.RetryError. Choose one retry layer to avoid multiplying attempts.

Rate-limit headers vary by provider. For a documented allowance of 60 requests per minute, spacing calls at least one second apart is a basic starting policy. Combine quota awareness, caching, bounded attempts and network timeouts when deciding how long a job can run.

Key Takeaways

  • Retry temporary failures only when repeating the operation is safe.
  • Bound attempts and use exponential backoff with jitter.
  • Honor both delay-seconds and HTTP-date forms of Retry-After.
  • Count attempts separately from retries and waits.
  • Combine retry delays, timeouts and quota limits into one run policy.
  • Avoid stacking independent retry layers.

5.3 Build a small, reliable API-to-file pipeline

A dependable pipeline turns configuration and remote data into a completed output file with a clear report. Keep stages separate so a failed fetch, invalid record or write error has an explicit effect on the run.

Define the stages and failure policy

Use small functions for configuration, fetching, validation and transformation, output, and reporting. Fetching includes timeout handling, safe retries and all required pages. Validate all retained records before touching the published output.

Choose the policy for bad records: stop the run, or skip each bad record and record its reason. If the API stays unreachable after retries, stop. A successful empty response and a failed fetch must have different outcomes. End a failed run with a nonzero exit code so a scheduler can detect it.

Reuse raw data deliberately

Cache a raw response under a name identifying the request, such as cache/forecast-lisbon-2026-11-03.json. A repeat run can load it instead of spending another request. Include relevant request parameters in the cache identity. Compare the modification time from path.stat().st_mtime with the current time when freshness matters; refresh or remove an expired entry.

Keep raw input separate from transformed output. This lets you repair a conversion and rerun it against the same data. A cache needs the same JSON-syntax and data-shape checks as a new response.

Turn validated forecasts into reusable rows

Suppose data is the validated Lisbon response with two forecasts, temperatures 18.5 and 19.0, and wind values {"speed_kmh": 14} and null. Parse timestamps as aware datetimes, normalize them to UTC, and keep absent optional wind as None:

from datetime import datetime, timezone

rows = []
for item in data["forecast"]:
    moment = datetime.fromisoformat(item["time"].replace("Z", "+00:00"))
    if moment.utcoffset() is None:
        raise ValueError("Forecast time needs a UTC offset")
    rows.append({
        "city": data["city"],
        "time_utc": moment.astimezone(timezone.utc).isoformat(),
        "temp_c": item["temp_c"],
        "wind_speed_kmh": (item.get("wind") or {}).get("speed_kmh"),
    })

The rows write as Lisbon,2026-11-03T12:00:00+00:00,18.5,14 and Lisbon,2026-11-03T15:00:00+00:00,19.0,. The last empty field means missing wind, not calm wind. If the source reports m/s, multiply by 3.6 before storing km/h; 5 m/s becomes 18 km/h.

Replace the output only when it is complete
import csv
from pathlib import Path

def write_rows(path, rows):
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_name(path.name + ".tmp")
    columns = ["city", "time_utc", "temp_c", "wind_speed_kmh"]
    with tmp.open("w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=columns)
        writer.writeheader()
        writer.writerows(rows)
    tmp.replace(path)

write_rows(Path("out") / "forecast-2026-11-03.csv", rows)

Validation protects against bad input before writing; a temporary file protects the previous output if writing fails. The with block closes the new file before replacement. One daily replacement file also makes reruns safe: repeating the same export does not append duplicate rows. An accumulating output instead needs a persistent set of record IDs to exclude records already stored.

Report records fetched, written and skipped, plus the reasons for skips and whether a cached response was used. Use units in column names, UTC ISO timestamps, UTF-8 and decimal points so another program can interpret the output without guessing.

Key Takeaways

  • Separate configuration, fetch, validation, output and reporting.
  • Cache by request identity and apply an explicit freshness policy.
  • Validate and transform all retained data before publishing output.
  • Write beside the destination, close, then replace.
  • Make reruns safe with replacement or persistent ID checks.
  • Preserve missing values, units and UTC offsets in output.
  • Use a nonzero exit code for failure and report skipped records.

Python JSON and CSV Files examples

5 Walkthroughs

1

Find an input and publish a completed report

10 steps
Follow a report from a stable input path through decoding, file discovery and safe output replacement.
  1. 1
    IntroductionGive a report a stable location

    A reporting script reads notes and saves a line-count report. It should find its inputs even when a scheduler starts it from another folder.

    First choose how to identify the project folder. Then use explicit text decoding, find the intended files, and publish the report only after it has been written successfully. Calculating a path and changing the file system are separate actions.

  2. 2
    ExplanationJoin path parts

    Start with from pathlib import Path. Then build a location with Path("notes") / "meeting.txt". The / operator supplies the system’s path separator; constructing this object does not create the notes folder or file.

    Use relative parts after a base folder. On Linux, joining Path("notes") / "/tmp/meeting.txt" selects the absolute /tmp/meeting.txt, discarding the earlier base.

  3. 3
    ExampleAnchor the input to the script

    Suppose the script is /home/ana/project/report.py. A plain relative Path("notes") depends on where the process starts.

    BASE = Path(__file__).resolve().parent
    src = BASE / "notes"
    

    resolve() locates the script absolutely, parent selects its folder, and the last join selects its notes folder. The input stays tied to the project when the working directory changes.

  4. 4
    ChallengePredict a changed file name

    For p = Path("records/visits.backup.csv"), what are p.stem and p.with_suffix(".json").name? Does p change?

    ---reveal---

    The stem is "visits.backup"; the new name is "visits.backup.json". Only the final suffix is removed or replaced. p remains unchanged because the operation returns a new Path.

  5. 5
    ExplanationDecode the input deliberately

    A file contains bytes, so reading text needs an encoding. p.read_text(encoding="utf-8") returns a whole string. For a large file, loop over an open text file instead of loading it all.

    If a UTF-8 export begins with a BOM, use utf-8-sig to remove that initial mark. Otherwise it can become part of the first word or CSV header. Explicit encoding also keeps behavior consistent on Python versions before 3.15.

  6. 6
    ExampleDiscover and count the notes

    For each p in sorted(src.glob("*.txt")), keep file entries and count len(p.read_text(encoding="utf-8").splitlines()). Append a line such as f"{p.name}: {count}" to a list.

    glob stays in this folder; rglob would also search subfolders. Sorting makes the report order repeatable. If a.txt has 3 lines and b.txt has 12, those become the two labeled counts.

  7. 7
    ExamplePrepare the output folder

    Choose an output beside the project and create its parent directories:

    out = BASE / "out" / "summary.txt"
    out.parent.mkdir(parents=True, exist_ok=True)
    text = "\n".join(lines) + "\n"
    

    Here lines is the list of labeled counts. parents=True creates missing ancestors; exist_ok=True accepts an existing folder. The last expression builds the complete report text before any output is replaced.

  8. 8
    ChallengeProtect yesterday’s complete report

    The report already exists. Why is out.write_text(text, encoding="utf-8") risky if the write fails, and what sequence protects the old output?

    ---reveal---

    Direct writing truncates the destination first. Write to a temporary path in the same folder, close it, then call tmp.replace(out). A failure before replacement leaves the old complete report at its destination.

  9. 9
    ChallengeKeep location and publication stable

    A scheduled run starts outside the project, and the new report cannot be fully written. What two choices let it find the intended notes and leave the published report intact?

    ---reveal---

    Build inputs from the script’s resolved parent folder, and write the output through a closed sibling temporary file before replacement. The first choice fixes location; the second protects publication. An existence check alone does neither.

  10. 10
    RecapMake each disk operation intentional

    Build paths from a deliberate base, inspect names with path attributes, and decode text explicitly. Discover files with the search scope and order the report needs.

    Prepare the report before publication, create its parent folders, and replace the destination only after the temporary output is complete and closed.

2

Convert a local-format table into clean CSV

12 steps
Read quoted fields, normalize prices and dates, report invalid records and write a consistent table.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionRead structure before interpreting values
  2. 2
    ExplanationLet the parser recognize fields
  3. 3
    ExampleUse names for columns
  4. 4
    ChallengeSeparate missing from zero
  5. 5
    ExampleRecognize the semicolon table
  6. 6
    ExampleNormalize the price text
  7. 7
    ExampleParse dates with their source meaning
  8. 8
    ChallengeChoose a conversion from evidence
  9. 9
    ExplanationWrite declared columns
  10. 10
    ChallengePredict quoting and formatting
  11. 11
    ChallengeFix two different rerun defects
  12. 12
    RecapKeep the table contract visible
3

Read a forecast and preserve its meaning

13 steps
Trace nested fields, handle nulls, normalize timestamps and save JSON without damaging an existing document.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionFollow a value from JSON text to a row
  2. 2
    ExplanationTranslate between JSON and Python
  3. 3
    ExampleCheck a round trip
  4. 4
    ChallengeReject an unsupported object deliberately
  5. 5
    ExplanationLoad a document and check its shape
  6. 6
    ExampleEncode before opening output
  7. 7
    ChallengeHandle a damaged saved response
  8. 8
    ExampleWalk the nested forecast
  9. 9
    Key InsightAn explicit null bypasses a default
  10. 10
    ExampleNormalize the timestamp
  11. 11
    ChallengeValidate a boolean reading
  12. 12
    ChallengeStore repeated records in the right format
  13. 13
    RecapKeep syntax, structure and time distinct
4

Make and inspect a paginated API request

12 steps
Build a request, protect its credential, interpret the response and collect all pages under an explicit API contract.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionRead the service’s contract
  2. 2
    ExplanationMatch the method to the operation
  3. 3
    ChallengeInterpret a refusal precisely
  4. 4
    ExampleRead the credential at startup
  5. 5
    ChallengeRespond to exposure
  6. 6
    ExampleSend the first page
  7. 7
    ExplanationInspect the expected representation
  8. 8
    ExampleAdvance and stop on the documented rule
  9. 9
    ChallengeRecognize the last request
  10. 10
    TipExplore without repeated calls
  11. 11
    ChallengeAvoid a false success after a page error
  12. 12
    RecapComplete the exchange deliberately
5

Recover safely and publish one complete export

15 steps
Choose timeout and retry behavior, validate a response, normalize its rows and protect the published file during a failed run.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionDecide what a failed run means
  2. 2
    ExplanationSet connection and read limits
  3. 3
    ExampleLocate the failure stage
  4. 4
    ChallengeChoose handler order
  5. 5
    ExplanationChoose failures worth retrying
  6. 6
    ExampleCount attempts and growing waits
  7. 7
    ExampleGive Retry-After priority
  8. 8
    ChallengeRecover from a temporary outage
  9. 9
    ConnectionUse the cache for the same request
  10. 10
    ExampleValidate before preparing rows
  11. 11
    ExampleKeep time and units clear
  12. 12
    ExampleClose the new file before publication
  13. 13
    ChallengeReport a write failure honestly
  14. 14
    ChallengeDiagnose the next day’s rerun
  15. 15
    RecapPublish data with an explainable outcome

Python JSON and CSV Files practice questions

50 Practice Questions in 5 sets

Set 1: Read files and interpret structured data10 Practice Questions

Question 1 of 10

What is Path("archive/visits.backup.csv").stem?
  1. "visits"
  2. "visits.backup.csv"
  3. "visits.backup"
  4. "archive/visits.backup"
Show answerHide answer
Answer: C
The stem removes the last suffix from the final path component, so the result is "visits.backup". It does not remove every suffix-like part: "visits" would discard both .backup and .csv. The parent folder is not included in the stem.

Question 2 of 10

What fields does csv.reader return for the record "Park, Mina",6,2.75 with the default dialect?
  1. ["Park, Mina", "6", "2.75"]
  2. ["Park", " Mina", "6", "2.75"]
  3. ["Park, Mina", 6, 2.75]
  4. ["Park, Mina,6,2.75"]
Show answerHide answer
Answer: A
The quotes make "Park, Mina" one field, and a normal CSV reader returns all three fields as strings. Splitting at every comma would break the name into two pieces. Numeric-looking text is not converted to numbers by the default reader.

Question 3 of 10

What Python value does json.loads("false") return?
  1. "false"
  2. None
  3. 0
  4. False
Show answerHide answer
Answer: D
The JSON literal false maps to Python’s boolean False. It is not the string "false", which would require JSON quotation marks around the word. Although False compares equal to zero in Python, the parser returns a boolean here, not an integer.

Question 4 of 10

A script at /opt/reports/run.py opens Path("input/counts.csv"). It is launched from /opt. Where does that relative path point?
  1. /opt/reports/input/counts.csv
  2. /opt/input/counts.csv
  3. /input/counts.csv
  4. /opt/reports/counts.csv
Show answerHide answer
Answer: B
The relative path starts at the current working directory, /opt, so it points to /opt/input/counts.csv. The script’s own directory does not become the base automatically. To select data beside the script, construct the path from Path(__file__).resolve().parent.

Question 5 of 10

A UTF-8 CSV header prints as "\ufeffstation", and row["station"] raises KeyError. What reading change addresses the cause?
  1. Use encoding="utf-8-sig" for this file.
  2. Use newline=None for this file.
  3. Use encoding="cp1252" for this file.
  4. Use skipinitialspace=True for this file.
Show answerHide answer
Answer: A
The leading \ufeff indicates a UTF-8 byte order mark that became part of the first header. Reading with utf-8-sig removes that mark while retaining UTF-8 decoding. Skipping spaces does not remove a BOM because it is not an ordinary space after a delimiter.

Question 6 of 10

A DictWriter has fieldnames=["site", "height_m"]. What data record is written from {"height_m": 82, "site": "North"}?
  1. site,height_m
  2. 82,North
  3. North,82
  4. A ValueError is raised.
Show answerHide answer
Answer: C
DictWriter follows fieldnames, so it writes the site before the height: North,82. The dictionary’s own insertion order does not override that column order. writerow() writes the supplied data record; writing the column names requires a separate writeheader() call.

Question 7 of 10

A source documents periods for thousands and commas for decimals. What value does its text "2.048,75" represent?
  1. 2.04875
  2. 204875.0
  3. 2.048
  4. 2048.75
Show answerHide answer
Answer: D
The period groups thousands, so remove it, leaving "2048,75"; changing the decimal comma gives "2048.75". The value is 2048.75. Treating the period as the decimal mark would produce a much smaller number and ignore the source’s stated convention.

Question 8 of 10

What is json.loads(json.dumps({7: (2, 5)}))?
  1. {7: (2, 5)}
  2. {"7": [2, 5]}
  3. {7: [2, 5]}
  4. {"7": (2, 5)}
Show answerHide answer
Answer: B
JSON object keys are strings, so the integer key becomes "7". The tuple is encoded as an array, and an array parses as a Python list. Keeping either the numeric key or the tuple would assume JSON preserves distinctions that its type system does not represent.

Question 9 of 10

A CSV has header code,qty,price, followed by R4,2,3.25, R5,4,, and R6,3. A program skips rows with an absent or empty price and totals valid quantity times price. What total and skip count should it report?
  1. 6.50, with one row skipped
  2. 6.50, with two rows skipped
  3. 9.75, with two rows skipped
  4. 6.50, with no rows skipped
Show answerHide answer
Answer: B
R4 contributes 2 times 3.25, giving 6.50. R5 has an empty price string and R6 has an absent field, which DictReader supplies as None, so both are skipped. Checking only for the empty string misses the short row and can lead to a conversion error.

Question 10 of 10

An existing settings file is {"theme":"dark"}. New data contains a nested set, and must replace it only after successful encoding and writing. What order meets that requirement?
  1. Open destination; dump data; close; replace it.
  2. Encode data; open destination; write; close it.
  3. Open temporary file; replace destination; dump data.
  4. Encode data; write and close a sibling temporary file; replace destination.
Show answerHide answer
Answer: D
Encoding first detects the unsupported set before any file is changed. Writing and closing a sibling temporary file then protects the existing destination against an interrupted write. Encoding first but writing directly to the destination still leaves the old file vulnerable to a write failure.
Set 2: Trace JSON values and HTTP exchanges10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

An open text file is stored in f. What call parses its single JSON document?
  1. json.loads(f)
  2. json.load(f)
  3. json.dumps(f)
  4. json.dump(f)
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What HTTP status means that a request succeeded and has no response content?
  1. 200
  2. 201
  3. 304
  4. 204
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What should a program do first after discovering that its API key was posted publicly?
  1. Revoke or rotate the exposed key.
  2. Delete the current source-code line.
  3. Move the same key into a .env file.
  4. Mask the key in future screenshots.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

For data = {"samples": [{"value": 12}, {"value": 17}]}, what expression retrieves 17?
  1. data["samples"][0]["value"]
  2. data["samples"]["value"][1]
  3. data["samples"][1]["value"]
  4. data[1]["samples"]["value"]
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

An endpoint requires a JSON object in the request body. A program passes payload as a dictionary using data=payload and receives 415. What change matches the required body format?
  1. Pass params=payload instead.
  2. Pass headers=payload instead.
  3. Pass json=payload instead.
  4. Pass auth=payload instead.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

An API timestamp is "2026-08-12T10:15:00+03:00". What UTC time represents the same moment?
  1. 13:15 on August 12
  2. 10:15 on August 12
  3. 07:15 on August 13
  4. 07:15 on August 12
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A resource is deleted successfully, and repeating the identical DELETE returns 404. What does this show about idempotency?
  1. The deletion can still be idempotent because the resource remains absent.
  2. The deletion is not idempotent because its status code changed.
  3. Only the second request is idempotent because it changes nothing.
  4. A 404 guarantees the first deletion never reached the server.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A server returns status 200 with an HTML maintenance page. A program calls raise_for_status() and then r.json(). Where does it fail?
  1. get() raises HTTPError.
  2. r.json() raises requests JSONDecodeError.
  3. raise_for_status() raises HTTPError.
  4. Parsing succeeds because the status is 200.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A response has {"wind": null, "temp_c": true}. Wind may be absent, null or an object; temperature must be a number, with booleans forbidden. What processing decision is correct?
  1. Reject wind and accept temperature as numeric.
  2. Accept both, writing wind as zero.
  3. Treat wind as missing and reject temperature.
  4. Reject both because JSON has no null or boolean.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

An API returns 40 records per page and stops on a short page. A client has a three-page guard. Its first three pages each return 40 records, but the actual collection has 120. What should the current client report?
  1. Success with 120 records after page 3.
  2. Unconfirmed completeness when the guard is reached.
  3. Success after treating page 3 as empty.
  4. A request failure because a full page is invalid.
Show answerHide answer

Save this lesson to see this answer.

Set 3: Handle API credentials and failures10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

What does requests do by default when no timeout is supplied?
  1. It sets a total ten-second limit.
  2. It sets a ten-second read timeout.
  3. It retries once per second.
  4. It imposes no default timeout.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

With the default CSV writer, how is the Python value None represented in a field?
  1. As the text None
  2. As the text null
  3. As an empty field
  4. As the number 0
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A program calls os.getenv("SENSOR_KEY"), but the environment variable is absent. What check avoids sending Bearer None?
  1. Stop at startup when the returned value is missing.
  2. Catch HTTPError before reading the environment variable.
  3. Convert the returned value to a string before sending it.
  4. Rename the Authorization header to Content-Type.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A GET receives 429 with Retry-After: 75. Its local backoff is four seconds. When may it retry under this policy?
  1. After the local backoff.
  2. After the smaller wait value.
  3. At once, on a new connection.
  4. After at least 75 seconds.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Handlers appear in this order: requests ConnectionError, then Timeout. A ConnectTimeout occurs. What handler runs?
  1. Only the Timeout handler.
  2. The ConnectionError handler.
  3. Both handlers, in order.
  4. Neither, because it is a built-in error.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A text file contains {"id": 21} on one line and {"id": 22} on the next. How should these JSON Lines records be parsed?
  1. Call json.load() twice on the same file.
  2. Wrap the file name in json.loads().
  3. Loop over nonblank lines and call json.loads(line).
  4. Call json.load() once and expect a list.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A request uses Accept: application/json and sends a JSON body. What header describes the format of that request body?
  1. Content-Type: application/json
  2. Accept: application/json
  3. Authorization: application/json
  4. Retry-After: application/json
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A batch job has three outcomes: a GET returns 503, a reservation POST loses its response, and repeating a successful DELETE returns 404. No creation idempotency mechanism exists. What recovery plan fits all three?
  1. Retry GET and POST; accept the resource as deleted.
  2. Retry GET; check the reservation; accept the resource as deleted.
  3. Retry GET; check the reservation; retry DELETE until 204.
  4. Stop GET; repeat POST; accept the resource as deleted.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A cp1252 file uses semicolons and day-first dates. A row is Aster;8,40;04/07/2026, where the comma marks decimals. What normalized values should it produce?
  1. Aster, 840, 2026-04-07
  2. Aster, 8.40, 2026-04-07
  3. Aster, 840, 2026-07-04
  4. Aster, 8.40, 2026-07-04
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A daily export validates all data, opens the existing output with "w", and runs out of disk space halfway through writing. What design change protects the previous completed export?
  1. Validate the data a second time before writing.
  2. Append the new data directly to the existing output.
  3. Write and close a sibling temporary file before replacement.
  4. Catch the write error and return an empty success report.
Show answerHide answer

Save this lesson to see this answer.

Set 4: Build exports that survive reruns10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

What Path method creates an output folder together with missing parent folders and accepts an existing directory?
  1. mkdir(parents=True, exist_ok=True)
  2. mkdir(parents=False, exist_ok=True)
  3. mkdir(parents=True, exist_ok=False)
  4. write_text("", encoding="utf-8")
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A program must reject nonfinite floats instead of writing nonstandard JSON. What encoder setting provides this behavior?
  1. ensure_ascii=False
  2. sort_keys=True
  3. allow_nan=False
  4. indent=2
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A CSV quantity is the string "12". What does quantity * 3 produce before conversion?
  1. The integer 36
  2. The string "121212"
  3. The string "36"
  4. A ValueError exception
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A Session sets Accept: application/json. One call passes headers={"Accept": "text/csv"}. What Accept value is sent on that call?
  1. Both values as separate headers.
  2. The session value application/json.
  3. The call-specific value text/csv.
  4. No Accept header because they conflict.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A GET policy allows four attempts and uses waits of 2, 4 and 8 seconds between them. How much waiting occurs if the fourth attempt succeeds?
  1. 14 seconds
  2. 16 seconds
  3. 30 seconds
  4. 8 seconds
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

An append script writes a CSV header on every run. After three runs, two headers appear among the data rows. What change prevents that?
  1. Switch from DictWriter to writer without changing the logic.
  2. Write a header only when the file is new or empty.
  3. Call writeheader after the data instead of before it.
  4. Set extrasaction to ignore on the writer.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A sensor supplies {"time":"2026-09-20T02:30:00+02:00","wind_mps":2.5}. A row must use UTC time and km/h. What values belong in it?
  1. 02:30+00:00, 9.0
  2. 00:30+00:00, 9.0
  3. 00:30+00:00, 0.6944
  4. 04:30+00:00, 2.5
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

An accumulating export stores IDs 31, 32 and 33. The next fetched batch has IDs 33, 34, 34 and 35. How many records should be added to keep IDs unique across runs and within the batch?
  1. Four records
  2. Three records
  3. One record
  4. Two records
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A nonstreaming GET uses timeout=(2, 6). Its body arrives in chunks three seconds apart for 30 seconds, then stalls for seven seconds. The only handler is Python’s built-in ConnectionError. What outcome is expected?
  1. The transfer can pass 30 seconds; the body stall can raise an uncaught requests ConnectionError.
  2. The six-second total limit raises ReadTimeout, which the built-in handler catches.
  3. The transfer can pass 30 seconds; the body stall returns None through the built-in handler.
  4. The two-second connect limit stops body reading before the first chunk arrives.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

On Linux, a program runs:

p = Path("/srv/jobs") / "/tmp/month.backup.csv"
p.with_suffix(".json")

What are p.parent and p.stem afterward?

  1. Path("/srv/jobs/tmp") and "month.backup"
  2. Path("/tmp") and "month"
  3. Path("/srv/jobs") and "month.backup"
  4. Path("/tmp") and "month.backup"
Show answerHide answer

Save this lesson to see this answer.

Set 5: Diagnose data and pipeline defects10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A DictWriter uses fieldnames=["id", "depth_m", "note"] and extrasaction="ignore". It receives {"note": None, "raw_tag": "x", "depth_m": "2.40", "id": "N7"}. What CSV record is written?
  1. N7,2.40,None
  2. ,2.40,N7
  3. N7,2.40,
  4. N7,2.40,,x
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What status indicates that the client has exceeded a service’s request rate limit?
  1. 403
  2. 503
  3. 429
  4. 422
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A script must find .csv entries throughout incoming, process files only, and use a stable alphabetical order. What expression supplies the intended paths?
  1. Path("incoming").glob("*.csv")
  2. sorted(p for p in Path("incoming").rglob("*.csv") if p.is_file())
  3. list(Path("incoming").iterdir())
  4. sorted(p for p in Path("incoming").glob("*.csv") if p.is_dir())
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A key was committed last week and removed today. A teammate says the repository is now safe to publish because the latest file has no key. What action is still required?
  1. Revoke the old key because earlier commits retain it.
  2. Add the file to .gitignore because that erases history.
  3. Move the same key to .env because that invalidates copies.
  4. Make the repository private because that voids the key.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A program parses {"count":4,"count":9} with default json.loads(). What result is retained?
  1. {"count": [4, 9]}
  2. A duplicate-key exception
  3. {"count": 4}
  4. {"count": 9}
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A semicolon CSV has header id;qty;price and records K1;3;2,50, K2;two;1,20, K3;4;1,25. Decimal commas are documented. Invalid quantities are skipped and reported. What total and skip count are correct?
  1. 12.50, with no rows skipped
  2. 10.00, with one row skipped
  3. 12.50, with one row skipped
  4. 1250.00, with one row skipped
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

An API sends A: {"time":"2026-06-18T08:00:00","value":false} and B: {"time":"2026-06-18T08:00:00+02:00","value":0}. Measurements must be numeric, and times must identify moments. What rows can be accepted, and at what UTC time?
  1. Both A and B, each at 08:00 UTC.
  2. Only B, at 06:00 UTC.
  3. Only A, at 08:00 UTC.
  4. Only B, at 10:00 UTC.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A safe GET returns 503 with an HTTP-date Retry-After 90 seconds ahead. The local backoff cap is 20 seconds, and the job may wait only 30 more seconds. What should it do?
  1. Retry after 20 seconds because only local backoff is capped.
  2. Retry after 30 seconds because the job budget overrides the header.
  3. Wait 90 seconds and still declare the 30-second budget respected.
  4. Stop or defer because the required wait exceeds the job budget.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

An API exposes cursor pages. A daily export appends each page as soon as it arrives. Page 3 fails, and a rerun starts again from page 1. What redesign prevents partial publication and rerun duplicates?
  1. Fetch and validate all pages; replace a completed daily file.
  2. Fetch and validate all pages; append them to the daily file.
  3. Replace the daily file after each page has been validated.
  4. Clear the daily file; fetch and validate all pages into it.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A cache file is named only by city. A script requests hourly and daily data for that city, each with a six-hour freshness limit. A fresh hourly response is reused for the daily request. What cache design fixes this error?
  1. Keep city-only keys and shorten every lifetime to one second.
  2. Key by city and relevant request parameters, and check age per entry.
  3. Keep city-only keys and accept any response younger than six hours.
  4. Key only by modification time, without recording the request.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

83 Key Terms, each with its definition

A

Absolute path
An absolute path identifies a location from the file system’s root or drive, so it does not depend on the current working directory.
On Linux, "/srv/data/stations.csv" starts at the root and names a complete location.
API key
An API key is a credential identifying an account or application to a service and granting access within the permissions attached to it.
A reporting script reads its key from the environment instead of storing a working credential in source code.
Append mode
Append mode writes new text at the end of an existing file, preserving earlier content but requiring care with headers and duplicate records.
An accumulating CSV uses mode "a" and adds a header only when the destination is new or empty.
Atomic replacement
An atomic replacement changes which complete file occupies a destination in one indivisible step, so readers do not see a partial mix.
After closing a sibling temporary file, replacing the report makes the completed new version visible.
Authentication
Authentication establishes the identity of a caller, using credentials such as a key or token accepted by the service.
A missing or invalid credential commonly produces 401 before the client can retrieve protected data.
Authorization
Authorization determines whether an identified caller is allowed to perform an action, based on permissions or other service rules.
A read-only key may retrieve a record while a request to modify it is refused by the service.
Aware datetime
An aware datetime carries time-zone information with a usable UTC offset, allowing it to identify a moment relative to other aware values.
A timestamp ending in +00:00 can be converted to a named local zone without losing its moment.

B

Byte order mark
A byte order mark is an initial Unicode marker that some UTF-8 exports include and that may otherwise become part of the first field.
Reading a spreadsheet export with utf-8-sig removes a BOM before the CSV header is parsed.

C

Cache
A cache stores a reusable copy of fetched data under an identity and freshness policy, reducing repeated requests and supporting repeatable processing.
Include relevant query settings in a cache name so an hourly response cannot satisfy a daily request.
Connect timeout
A connect timeout bounds the wait while establishing a network connection, separately from the time allowed for receiving response data.
In timeout=(4, 12), four seconds is the connection setting and twelve is the read setting.
Content-Type
Content-Type is a header that identifies the format of a message’s representation, helping the receiver choose how to interpret its body.
A JSON submission uses application/json; requesting JSON with Accept does not set the body format.
Credential rotation
Credential rotation replaces an existing key or token with a new one and invalidates the old credential to prevent its continued use.
After an exposed key is revoked, update the configured environment with the replacement credential.
CSV
CSV is a plain-text table format whose records contain delimited fields, with quoting rules for embedded separators and line breaks.
A quoted full name can contain a comma while still occupying just one field in a CSV record.
Current working directory
The current working directory is the process’s starting location for relative file operations, which may differ from the script’s own folder.
Printing Path.cwd() helps explain why an input was found in a terminal but missed by a scheduler.

D

Data pipeline
A data pipeline is a sequence of stages that obtains data, validates and transforms it, saves usable results and reports the run’s outcome.
Separating fetch and save stages keeps an unreachable API from becoming a successful empty export.
Date format
A date format specifies which text components stand for year, month and day, preventing ambiguous dates from being interpreted by guesswork.
Parsing "08/11/2026" as day-first gives November 8; month-first parsing gives August 11.
Decimal
A Decimal is a Python decimal-number object that supports exact decimal arithmetic when values are constructed from their original text.
Decimal("0.15") + Decimal("0.25") preserves the intended decimal sum for an amount.
Decimal mark
A decimal mark separates the whole-number and fractional parts of a number’s text representation and must match the source convention.
A source using decimal commas writes eight and a half as "8,5", which needs conversion before float parsing.
Default hook
A default hook is a JSON encoder function called for unsupported objects, returning an encodable replacement or raising TypeError.
A focused hook can encode a datetime as ISO text while rejecting an unexpected custom object.
Delimiter
A delimiter separates fields in a text table; commas, semicolons and tabs are common choices that the parser must distinguish from field content.
For "item;mass_kg", setting delimiter=";" gives two fields instead of one combined header.
Deserialization
Deserialization parses a stored or transmitted representation into usable in-memory values, such as building dictionaries and lists from JSON.
After json.loads(text), an array of record objects becomes a Python list of dictionaries.
Dialect
A CSV dialect is a collection of formatting settings, including delimiter, quote behavior and record terminators, used to parse or write a table.
A semicolon export needs a matching delimiter even when its file extension is still .csv.
DictReader
A DictReader is a CSV reader that produces a dictionary for each record, normally taking its keys from the first record’s header.
A short record receives None for a missing field, while a present empty field remains "".
DictWriter
A DictWriter writes dictionary records to CSV using an explicit sequence of field names to determine which columns appear and in what order.
A writer with fieldnames=["site", "depth_m"] outputs the site first even if the row’s keys are reversed.

E

Encoding
An encoding defines how text characters are represented as bytes, so a reader must use the intended encoding to recover the text.
Reading UTF-8 bytes as cp1252 can turn the name "René" into text containing "é".
Environment variable
An environment variable is a named setting supplied outside a program and read at runtime, keeping configuration separate from source text.
If os.getenv("REPORT_KEY") is empty, the script stops before building its authorization header.
Exception chaining
Exception chaining attaches an original error as the cause of a new error, preserving debugging context while giving the caller a clearer message.
raise RuntimeError("Fetch failed") from e keeps the original cause attached to the reported failure.
Exit code
An exit code is a process result supplied to its caller, normally zero for success and nonzero when the program reports failure.
A scheduler can detect an exhausted fetch failure when the script ends with SystemExit(1).
Exponential backoff
Exponential backoff grows successive retry delays by a fixed factor, reducing repeated pressure on a service while bounding attempts and waits.
A base of two seconds with doubling gives waits of 2, 4 and 8 seconds before three further attempts.

F

Flattened row
A flattened row collects selected nested fields into a table record, with clear column names for shared values, units and optional measurements.
A row can repeat the station name beside a UTC time and write absent wind as an empty field.
Flattening
Flattening turns nested records into rows with selected fields, often repeating shared data and giving nested values explicit column names.
A forecast row repeats its city and stores a nested speed in the wind_speed_kmh column.

G

Glob pattern
A glob pattern describes matching path names with wildcards, allowing a program to discover entries without naming each one separately.
The pattern "*.json" finds JSON-named entries in a folder; rglob() also visits its subfolders.

H

Header
A header is a record of column names that a reader can use to identify the meaning of each field in later data records.
DictReader can access row["distance_m"] even after the distance column moves in a new export.
HTTP request
An HTTP request is a client message describing an operation through its method, URL, headers and, where needed, a body.
A search request can put its filters in query parameters and its access credential in a header.
HTTP response
An HTTP response is a server message containing a status code, headers and a body that may represent success data or an error.
A 404 can still have a valid JSON body explaining why the requested resource was not found.
HTTPError
An HTTPError is the requests exception raised by raise_for_status() for a 4xx or 5xx response, with the response available for inspection.
A 401 Response becomes an HTTPError only when the program explicitly checks it with raise_for_status().

I

IANA time zone
An IANA time zone is a named region whose database rules describe its changing UTC offsets, including applicable daylight-saving transitions.
ZoneInfo("Europe/Amsterdam") applies the date’s offset when displaying a UTC measurement locally.
Idempotency
Idempotency means repeating the same request has the same intended effect as one request, even if later responses have different statuses.
Deleting an already deleted record can return 404 while leaving the resource absent as intended.
Idempotency key
An idempotency key identifies a logical operation so a supporting API can recognize repeated submissions and avoid applying their effects twice.
A client uses the provider’s documented key mechanism before safely retrying an uncertain creation request.
ISO 8601
ISO 8601 is a family of date and time representations that includes year-month-day dates and timestamps with explicit UTC offsets.
The timestamp "2026-12-02T16:20:00+01:00" records both a clock reading and its offset from UTC.

J

Jitter
Jitter adds a small random component to retry delays so many clients do not repeatedly reach the service at the same instant.
Two clients using the same backoff schedule can still wake at slightly different times after jitter.
JSON
JSON is a structured text format supporting objects, arrays, strings, numbers, booleans and null, with rules distinct from Python literals.
A JSON response can hold an object containing a list of readings and a null optional measurement.
JSON array
A JSON array is an ordered sequence of values enclosed in square brackets, parsed as a Python list even when originally encoded from a tuple.
The tuple (4, 8) becomes the JSON array [4, 8] and returns to Python as a list.
JSON document
A JSON document is one complete serialized JSON value, which can be an object, array or scalar rather than necessarily a table of records.
A valid top-level string still needs rejection when the settings loader expects a dictionary.
JSON Lines
JSON Lines stores one complete JSON value per line, allowing record-by-record reading and appending without rewriting one large array.
A line loop calls json.loads(line) for each record instead of parsing the whole file with load().
JSON object
A JSON object is a collection of string-named values enclosed in braces, normally parsed as a Python dictionary by the json module.
Encoding an integer dictionary key changes it to a JSON string key, so it returns as text.
JSONDecodeError
A JSONDecodeError reports a JSON syntax failure and provides message and position attributes to help locate the invalid text.
The loader can show its line and column while keeping a damaged settings file available for repair.

L

Least privilege
Least privilege gives a credential only the access its program requires, limiting the damage if that credential is exposed or misused.
Use a separate read-only key for an export job that never needs to create or delete resources.
Line terminator
A line terminator is the character sequence a CSV writer adds after each record; the default Excel dialect uses carriage return and newline.
Opening output with newline="" prevents Windows from translating the writer’s \r\n a second time.

N

Naive datetime
A naive datetime lacks a usable UTC offset, so its clock reading alone does not say whether it represents UTC or a particular local time.
Removing an offset to compare a timestamp with a naive value loses the information needed for the comparison.
Nonfinite number
A nonfinite number is a special numeric value such as NaN or infinity, which Python can encode by default although standard JSON excludes it.
Using allow_nan=False stops an export instead of writing a value another JSON reader may reject.
Null
Null is JSON’s explicit empty value, parsed as Python None, and it differs from both an absent key and a measured numeric zero.
An explicit null wind field is returned by .get() even when that call supplies an empty-object default.

P

Page guard
A page guard is a limit that stops an unexpectedly long pagination loop and reports that completion was not established.
Reaching the guard raises an error instead of returning a partial collection as if it were complete.
Pagination
Pagination divides a collection into response-sized batches that a client retrieves through page numbers, offsets, cursors or next links.
A client advances the cursor until the response no longer supplies the next link required by its API.
Path
A Path is an object representing a file-system location, with operations for joining parts and inspecting names on the current system.
Path("inputs") / "stations.csv" builds a location without creating the input file.
Pure path
A pure path performs path calculations without accessing the file system and can use another operating system’s path conventions.
PureWindowsPath can inspect a Windows drive path while the Python program runs on macOS.

Q

Query parameter
A query parameter is a named value in the query portion of a URL, commonly used for filtering, searching or selecting a page.
Passing params={"q": "rock & soil"} lets requests encode the ampersand as part of the search value.
Quoting
Quoting encloses CSV fields containing special characters so a delimiter or line break inside a value is not treated as record structure.
The writer quotes "Reed, Jo" and doubles any double quotes embedded inside a quoted field.

R

Rate limit
A rate limit restricts how many requests a client may make within a time window, with quota details and enforcement defined by the provider.
A pipeline combines request spacing and cached responses to avoid exceeding its documented allowance.
Read timeout
A read timeout limits waiting for incoming response data, so it does not impose a deadline on a download that keeps making progress.
A response sending bytes regularly can take longer overall than the configured read timeout.
Record
A record is one logical row of CSV fields, which can span several physical lines when a quoted field contains a line break.
A multiline address still belongs to one customer record even though it occupies two source lines.
Relative path
A relative path identifies a location from a chosen starting directory, normally the current working directory when a file is opened.
Starting the same script from a different folder can change where "inputs/stations.csv" points.
Request body
A request body is the data sent with an HTTP operation, whose representation must match the format expected by the endpoint.
Passing a dictionary through json= sends a JSON representation instead of form-encoded fields.
RequestException
A RequestException is the common base class for requests-specific failures, enabling a final general handler after specific cases.
A Timeout handler must appear before RequestException if timeouts need their own recovery behavior.
Response object
A Response object exposes an HTTP result in requests, including status, headers, raw bytes, decoded text and JSON parsing operations.
The program calls raise_for_status() before treating r.json() as a successful data response.
REST
REST is an API design style centered on resources, standard HTTP operations and stateless requests carrying the needed request context.
A service can use GET on /devices/18 to read a device and PUT on that URL to replace it.
Retry-After
Retry-After is a response header giving delay-seconds or an HTTP date that tells a client when another attempt may be made.
A client honors a 45-second server delay even when its next local backoff would be only four seconds.
Run report
A run report records what a pipeline did, including fetched, written and skipped records, skip reasons and relevant cache or failure information.
Reporting two skipped invalid measurements makes a smaller output count explainable to its reader.

S

Safe rerun
A safe rerun repeats a pipeline without adding unintended duplicate effects, using replacement outputs or a persistent record-identity check.
Replacing the completed file for one date prevents that day’s readings from being appended twice.
Serialization
Serialization converts an in-memory value into a representation that can be stored or sent, such as encoding a Python dictionary as JSON text.
json.dumps({"ready": True}) produces text with JSON’s lowercase true literal.
Session
A requests Session maintains shared settings and reuses connections across calls, making a sequence of requests more convenient and efficient.
One session can apply the same Accept header while collecting every page from a collection.
Sniffer
A Sniffer is a CSV utility that estimates dialect or header properties from a text sample, so its result is a guess that needs checking.
After sampling the first 1024 characters, rewind the open file before passing it to a CSV reader.
Status code
A status code is a three-digit HTTP result whose class and specific value help a client decide how to interpret or handle a response.
A client treats 204 as success without content and avoids calling its JSON parser on the empty body.
Suffix
A suffix is the last extension-like part of a path’s final name, including its leading dot and preserving its original letter case.
For readings.backup.CSV, .suffix.lower() is ".csv" and .stem is "readings.backup".

T

Thousands separator
A thousands separator groups digits in a written number and must be removed according to the source’s convention before numeric parsing.
In a documented decimal-comma source, "6.200,40" becomes "6200.40" after the grouping period is removed.
TLS verification
TLS verification checks the server’s certificate to authenticate the endpoint during an encrypted connection, protecting against impersonation.
Keep requests verification enabled instead of bypassing a certificate error when sending an API key.
Transient failure
A transient failure is a problem that may succeed on a later attempt, such as a temporary service outage, rather than requiring a changed request.
A safe GET returning 503 can be retried after an appropriate delay under a bounded retry policy.
Type conversion
A type conversion turns a value into the representation a calculation needs, such as converting a CSV quantity string into an integer.
Without int(row["count"]), multiplying a count string by two repeats its text instead of doubling it.

U

Unix timestamp
A Unix timestamp commonly counts seconds from 1970-01-01 00:00 UTC, although some APIs supply milliseconds and require a unit conversion.
Before fromtimestamp(), divide a documented millisecond timestamp by 1000 and specify UTC.
UTC
UTC is the common time standard used to normalize moments from different offsets before storing, comparing or exchanging them.
A measurement at 11:00 with offset +02:00 is stored as 09:00 UTC for comparison with other sites.
UTF-8
UTF-8 is a text encoding that represents Unicode characters using variable numbers of bytes and is widely used for data exchange.
Passing encoding="utf-8" makes an exported report’s text encoding explicit across computers.

V

Validation
Validation checks whether parsed data satisfies the program’s requirements, including required fields, value types and acceptable shapes.
A settings object can parse correctly yet fail validation because its page size is a list.

W

Web API
A web API is a network interface through which programs request data or actions from a service, typically exchanging HTTP messages.
A reporting client asks a documented endpoint for readings instead of opening a page for a person.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started