- Learn
- Computer Science & IT
- Programming
- Intermediate Python
- Python JSON and CSV Files
Python JSON and CSV Files: Reading Data and Web APIs
IntermediateLesson 5 of 9 in Intermediate Python Course
What you will learn
- 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 pathlibCreate paths with
Pathand the/operator, take them apart into name, stem, suffix and parent, and see how relative paths are resolved. - Read, write and organize files and foldersCheck whether files exist, list and create folders, read and write whole text files with the right encoding, and replace files safely.
- Build and inspect paths with pathlib
- 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 dictionariesRead CSV files with
csv.readerandcsv.DictReader, convert the text values to numbers, and deal with empty or invalid fields. - Write CSV files with csv.writer and csv.DictWriterWrite 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 formatsRead and write CSV files that use semicolons, tabs, decimal commas, day-first dates or legacy encodings, and convert them to clean values.
- Read CSV files into rows and dictionaries
- 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 textKnow the JSON value types and syntax rules, use
json.dumpsandjson.loads, and predict how Python types change on the way to JSON and back. - Read and write JSON files safelyLoad 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 timesExtract values from nested API data, handle missing and null fields, flatten records into rows, and parse timestamps into time-zone-aware datetimes.
- Convert between Python objects and JSON text
- 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 APIsDescribe the parts of an HTTP request and response, interpret status codes, and map REST operations to HTTP methods.
- Call APIs with the requests librarySend 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 codeSend API keys and tokens the way an API expects, load them from the environment, and prevent, detect and repair leaks.
- Understand HTTP requests, responses and REST APIs
- 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 errorsGive every request a timeout, turn error status codes into exceptions, and catch the requests exceptions in the right order.
- Retry failures and respect rate limitsTell 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 pipelineCombine configuration, requests, validation, conversion and file output into one program that can be rerun safely and reports what it did.
- Set timeouts and handle request errors
Python JSON and CSV Files study guide
1Find, 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"):
| Expression | Result |
|---|---|
p.name | "sales.tar.gz" |
p.stem | "sales.tar" |
p.suffix | ".gz" |
p.suffixes | [".tar", ".gz"] |
p.parent | Path("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
Pathand/; construction does not create a file. - Relative paths start at the working directory; use an explicit base when location must be stable.
stemremoves 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-sigremoves 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 andrmdir()for empty folders.
2Read 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
csvhandle quoting and multiline records. - Open CSV text with
newline=""and an explicit encoding. DictReaderuses 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
Decimalfrom 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
| Mode | Effect | Header handling |
|---|---|---|
"w" | Starts a replacement table | Write one header at the start |
"a" | Adds to the existing file | Write 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.fieldnamescontrols 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.
3Serialize 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.
| Function | Direction |
|---|---|
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.
dumpsandloadswork with strings;dumpandloadwork with files.- Tuples return as lists and numeric object keys return as strings.
- Convert unsupported types deliberately or provide a focused
defaulthook. - Use
allow_nan=Falsefor standard JSON output. - Use
parse_float=Decimalwhen 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.
4Request 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
| Codes | Meaning |
|---|---|
| 1xx | Informational |
| 2xx | Success |
| 3xx | Redirection or cache-related response |
| 4xx | A client-side request problem |
| 5xx | A 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.
| Request | Typical purpose |
|---|---|
GET /books | List books |
GET /books/42 | Read one book |
POST /books | Create a book |
PUT /books/42 | Replace a book |
PATCH /books/42 | Change selected fields |
DELETE /books/42 | Remove 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 method | Result |
|---|---|
r.status_code | Integer status code |
r.headers | Case-insensitive response headers |
r.text | Decoded body text |
r.content | Raw 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
paramsfor query strings andjsonfor a JSON request body. - Check status, parse the expected body, then validate its structure.
r.text,r.contentandr.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.
5Handle 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
1Find an input and publish a completed report
10 steps
- 1IntroductionGive 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.
- 2ExplanationJoin path parts
Start with
from pathlib import Path. Then build a location withPath("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. - 3ExampleAnchor the input to the script
Suppose the script is
/home/ana/project/report.py. A plain relativePath("notes")depends on where the process starts.BASE = Path(__file__).resolve().parent src = BASE / "notes"resolve()locates the script absolutely,parentselects its folder, and the last join selects its notes folder. The input stays tied to the project when the working directory changes. - 4ChallengePredict a changed file name
For
p = Path("records/visits.backup.csv"), what arep.stemandp.with_suffix(".json").name? Doespchange?---reveal---
The stem is
"visits.backup"; the new name is"visits.backup.json". Only the final suffix is removed or replaced.premains unchanged because the operation returns a new Path. - 5ExplanationDecode 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-sigto 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. - 6ExampleDiscover and count the notes
For each
pinsorted(src.glob("*.txt")), keep file entries and countlen(p.read_text(encoding="utf-8").splitlines()). Append a line such asf"{p.name}: {count}"to a list.globstays in this folder;rglobwould also search subfolders. Sorting makes the report order repeatable. Ifa.txthas 3 lines andb.txthas 12, those become the two labeled counts. - 7ExamplePrepare 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
linesis the list of labeled counts.parents=Truecreates missing ancestors;exist_ok=Trueaccepts an existing folder. The last expression builds the complete report text before any output is replaced. - 8ChallengeProtect 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. - 9ChallengeKeep 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.
- 10RecapMake 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.
2Convert a local-format table into clean CSV
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionRead structure before interpreting values
- 2ExplanationLet the parser recognize fields
- 3ExampleUse names for columns
- 4ChallengeSeparate missing from zero
- 5ExampleRecognize the semicolon table
- 6ExampleNormalize the price text
- 7ExampleParse dates with their source meaning
- 8ChallengeChoose a conversion from evidence
- 9ExplanationWrite declared columns
- 10ChallengePredict quoting and formatting
- 11ChallengeFix two different rerun defects
- 12RecapKeep the table contract visible
3Read a forecast and preserve its meaning
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionFollow a value from JSON text to a row
- 2ExplanationTranslate between JSON and Python
- 3ExampleCheck a round trip
- 4ChallengeReject an unsupported object deliberately
- 5ExplanationLoad a document and check its shape
- 6ExampleEncode before opening output
- 7ChallengeHandle a damaged saved response
- 8ExampleWalk the nested forecast
- 9Key InsightAn explicit null bypasses a default
- 10ExampleNormalize the timestamp
- 11ChallengeValidate a boolean reading
- 12ChallengeStore repeated records in the right format
- 13RecapKeep syntax, structure and time distinct
4Make and inspect a paginated API request
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionRead the service’s contract
- 2ExplanationMatch the method to the operation
- 3ChallengeInterpret a refusal precisely
- 4ExampleRead the credential at startup
- 5ChallengeRespond to exposure
- 6ExampleSend the first page
- 7ExplanationInspect the expected representation
- 8ExampleAdvance and stop on the documented rule
- 9ChallengeRecognize the last request
- 10TipExplore without repeated calls
- 11ChallengeAvoid a false success after a page error
- 12RecapComplete the exchange deliberately
5Recover safely and publish one complete export
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionDecide what a failed run means
- 2ExplanationSet connection and read limits
- 3ExampleLocate the failure stage
- 4ChallengeChoose handler order
- 5ExplanationChoose failures worth retrying
- 6ExampleCount attempts and growing waits
- 7ExampleGive Retry-After priority
- 8ChallengeRecover from a temporary outage
- 9ConnectionUse the cache for the same request
- 10ExampleValidate before preparing rows
- 11ExampleKeep time and units clear
- 12ExampleClose the new file before publication
- 13ChallengeReport a write failure honestly
- 14ChallengeDiagnose the next day’s rerun
- 15RecapPublish data with an explainable outcome
Python JSON and CSV Files practice questions
Set 1: Read files and interpret structured data10 Practice Questions
Question 1 of 10
Path("archive/visits.backup.csv").stem?Show answerHide answer
"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
csv.reader return for the record "Park, Mina",6,2.75 with the default dialect?Show answerHide answer
"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
json.loads("false") return?Show answerHide answer
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
/opt/reports/run.py opens Path("input/counts.csv"). It is launched from /opt. Where does that relative path point?Show answerHide answer
/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
"\ufeffstation", and row["station"] raises KeyError. What reading change addresses the cause?Show answerHide answer
\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
fieldnames=["site", "height_m"]. What data record is written from {"height_m": 82, "site": "North"}?Show answerHide answer
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
"2.048,75" represent?Show answerHide answer
"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
json.loads(json.dumps({7: (2, 5)}))?Show answerHide answer
"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
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?Show answerHide answer
Question 10 of 10
{"theme":"dark"}. New data contains a nested set, and must replace it only after successful encoding and writing. What order meets that requirement?Show answerHide answer
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
f. What call parses its single JSON document?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
data = {"samples": [{"value": 12}, {"value": 17}]}, what expression retrieves 17?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
payload as a dictionary using data=payload and receives 415. What change matches the required body format?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
"2026-08-12T10:15:00+03:00". What UTC time represents the same moment?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
raise_for_status() and then r.json(). Where does it fail?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
{"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?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
None represented in a field?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
os.getenv("SENSOR_KEY"), but the environment variable is absent. What check avoids sending Bearer None?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Retry-After: 75. Its local backoff is four seconds. When may it retry under this policy?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
ConnectionError, then Timeout. A ConnectTimeout occurs. What handler runs?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
{"id": 21} on one line and {"id": 22} on the next. How should these JSON Lines records be parsed?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Accept: application/json and sends a JSON body. What header describes the format of that request body?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Aster;8,40;04/07/2026, where the comma marks decimals. What normalized values should it produce?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
"w", and runs out of disk space halfway through writing. What design change protects the previous completed export?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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
"12". What does quantity * 3 produce before conversion?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Accept: application/json. One call passes headers={"Accept": "text/csv"}. What Accept value is sent on that call?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
{"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?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
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?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?
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
.csv entries throughout incoming, process files only, and use a stable alphabetical order. What expression supplies the intended paths?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
{"count":4,"count":9} with default json.loads(). What result is retained?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Absolute path
"/srv/data/stations.csv" starts at the root and names a complete location.API key
Append mode
"a" and adds a header only when the destination is new or empty.Atomic replacement
Authentication
Authorization
Aware datetime
+00:00 can be converted to a named local zone without losing its moment.B
Byte order mark
utf-8-sig removes a BOM before the CSV header is parsed.C
Cache
Connect timeout
timeout=(4, 12), four seconds is the connection setting and twelve is the read setting.Content-Type
application/json; requesting JSON with Accept does not set the body format.Credential rotation
CSV
Current working directory
Path.cwd() helps explain why an input was found in a terminal but missed by a scheduler.D
Data pipeline
Date format
"08/11/2026" as day-first gives November 8; month-first parsing gives August 11.Decimal
Decimal("0.15") + Decimal("0.25") preserves the intended decimal sum for an amount.Decimal mark
"8,5", which needs conversion before float parsing.Default hook
Delimiter
"item;mass_kg", setting delimiter=";" gives two fields instead of one combined header.Deserialization
json.loads(text), an array of record objects becomes a Python list of dictionaries.Dialect
.csv.DictReader
None for a missing field, while a present empty field remains "".DictWriter
fieldnames=["site", "depth_m"] outputs the site first even if the row’s keys are reversed.E
Encoding
Environment variable
os.getenv("REPORT_KEY") is empty, the script stops before building its authorization header.Exception chaining
raise RuntimeError("Fetch failed") from e keeps the original cause attached to the reported failure.Exit code
SystemExit(1).Exponential backoff
F
Flattened row
Flattening
wind_speed_kmh column.G
Glob pattern
"*.json" finds JSON-named entries in a folder; rglob() also visits its subfolders.H
Header
row["distance_m"] even after the distance column moves in a new export.HTTP request
HTTP response
HTTPError
I
IANA time zone
ZoneInfo("Europe/Amsterdam") applies the date’s offset when displaying a UTC measurement locally.Idempotency
Idempotency key
ISO 8601
"2026-12-02T16:20:00+01:00" records both a clock reading and its offset from UTC.J
Jitter
JSON
JSON array
(4, 8) becomes the JSON array [4, 8] and returns to Python as a list.JSON document
JSON Lines
json.loads(line) for each record instead of parsing the whole file with load().JSON object
JSONDecodeError
L
Least privilege
Line terminator
newline="" prevents Windows from translating the writer’s \r\n a second time.N
Naive datetime
Nonfinite number
allow_nan=False stops an export instead of writing a value another JSON reader may reject.Null
.get() even when that call supplies an empty-object default.P
Page guard
Pagination
Path
Path("inputs") / "stations.csv" builds a location without creating the input file.Pure path
PureWindowsPath can inspect a Windows drive path while the Python program runs on macOS.Q
Query parameter
params={"q": "rock & soil"} lets requests encode the ampersand as part of the search value.Quoting
"Reed, Jo" and doubles any double quotes embedded inside a quoted field.R
Rate limit
Read timeout
Record
Relative path
"inputs/stations.csv" points.Request body
json= sends a JSON representation instead of form-encoded fields.RequestException
Response object
raise_for_status() before treating r.json() as a successful data response.REST
/devices/18 to read a device and PUT on that URL to replace it.Retry-After
Run report
S
Safe rerun
Serialization
json.dumps({"ready": True}) produces text with JSON’s lowercase true literal.Session
Sniffer
Status code
Suffix
readings.backup.CSV, .suffix.lower() is ".csv" and .stem is "readings.backup".T
Thousands separator
"6.200,40" becomes "6200.40" after the grouping period is removed.TLS verification
Transient failure
Type conversion
int(row["count"]), multiplying a count string by two repeats its text instead of doubling it.U
Unix timestamp
fromtimestamp(), divide a documented millisecond timestamp by 1000 and specify UTC.UTC
UTF-8
encoding="utf-8" makes an exported report’s text encoding explicit across computers.V
Validation
W
Web API
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.