Skip to content

Lesson 32 of 52Python power tools

Files and JSON

Read and write text files safely with pathlib, handle encodings, and parse JSON, JSON Lines and CSV.

22 min read0/7 questions

This unit puts the language to work on everyday jobs, starting with the one nearly every script needs. Sooner or later every program touches files: config files, logs, CSV exports from a spreadsheet, JSON from an API, a 2 GB data dump. Doing it right means closing files, choosing the right encoding, and not loading a huge file into memory at once. These are also the bread and butter of take-home tasks ("parse this log file and report...").

Opening, reading and writing

open(path, mode) returns a file object. Always use it in a with block (you built your own in Context Managers) so the file is closed even if something fails.

Python
with open("todo.txt", "w", encoding="utf-8") as f: f.write("buy milk\n") f.write("write tests\n") with open("todo.txt", "a", encoding="utf-8") as f: # append print("ship it", file=f) # print can write to files with open("todo.txt", encoding="utf-8") as f: # "r" is the default content = f.read() print(repr(content))print(content.splitlines())
Output
Press Run (⌘ Enter) to see what happens.
ModeMeaning
"r"Read text (default). Fails if the file does not exist.
"w"Write text. Creates or truncates (empties) the file.
"a"Append text to the end. Creates the file if needed.
"x"Create a new file; fails if it already exists. Safe against overwriting.
"rb", "wb"Binary: read or write raw bytes (images, zip files).
"r+"Read and write an existing file.

write does not add a newline for you, unlike print. And "w" destroys the old contents the moment the file opens, before you write anything.

Quick check
report.txt contains 100 lines. You run open("report.txt", "w") and then your program crashes before writing. What is in the file now?
Need a nudge? A hint rules out a wrong answer.

Encodings: text is bytes underneath

Files on disk hold bytes. A text file is bytes plus an encoding, the rule that maps bytes to characters. UTF-8 is the standard today: it covers every language and emoji, and plain English letters take one byte each.

From disk to Python objects
  1. b'{"name": "Zo\xc3\xab"}'raw bytes on disk
  2. decode with encoding="utf-8"open(..., encoding="utf-8") does this for you
  3. '{"name": "Zoë"}'a Python str (text)
  4. json.loads(text)parse the text format
  5. {'name': 'Zoë'}a Python dict you can use

ë is two bytes in UTF-8: \xc3\xab. Decoding with the right encoding turns bytes into characters.

1/3

The default encoding for open depends on the operating system (it is not UTF-8 on some Windows setups), so always pass encoding="utf-8" for text files. Code that works on your Mac and breaks on a colleague's Windows laptop usually forgot this.

Python
text = "Zoë says héllo"data = text.encode("utf-8")print(data, len(text), len(data)) # more bytes than charactersprint(data.decode("utf-8"))print(data.decode("latin-1")) # wrong encoding: garbled, not an error
Output
Press Run (⌘ Enter) to see what happens.

UTF-8 is the default in 3.15, and you still pass encoding=

Python 3.15 (October 2026) made UTF-8 the default text encoding everywhere (PEP 686), so open("notes.txt") no longer depends on the Windows code page. Keep writing encoding="utf-8" anyway, for three reasons. Your code may still run on 3.14 or older, where the default really is platform-dependent. Users can switch the old behaviour back with PYTHONUTF8=0. And an explicit argument tells the next reader that you thought about it. Linters such as Ruff and pylint have a rule that flags open() without an encoding (unspecified-encoding); turn it on.

Two more knobs matter in real data. errors="replace" swaps undecodable bytes for a replacement character instead of crashing, which is right for reading messy logs and wrong for anything you will write back. And files saved by Excel or old Windows tools often start with a BOM (byte order mark, the bytes EF BB BF). Open those with encoding="utf-8-sig", or your first CSV header comes out as "name" and row["name"] raises KeyError. What Changed in Python 3.11 to 3.15 lists the other 3.15 changes.

Binary files and bytes

Not every file is text. Images, PDFs, zip archives, database files and anything you hash or upload are binary: you want the raw bytes, with no decoding. Open with "rb" or "wb" and you get and give bytes objects instead of str. Do not pass encoding= in binary mode; it is an error.

Python
import hashlibfrom pathlib import Path # A tiny fake PNG: the 8-byte signature every PNG file starts with, then junkPath("logo.png").write_bytes(b"\x89PNG\r\n\x1a\n" + bytes(range(256)) * 400) with open("logo.png", "rb") as f: # "rb": no decoding, you get bytes header = f.read(8)print(header, type(header).__name__, len(header))print("is a PNG:", header == b"\x89PNG\r\n\x1a\n")print(header[1], header[1:4]) # indexing bytes gives an int, slicing gives bytes def sha256_of(path, chunk_size=64 * 1024): digest = hashlib.sha256() with open(path, "rb") as f: while chunk := f.read(chunk_size): # b"" at end of file is falsy digest.update(chunk) return digest.hexdigest() print(sha256_of("logo.png")[:16], Path("logo.png").stat().st_size, "bytes")with open("logo.png", "rb") as f: print(hashlib.file_digest(f, "sha256").hexdigest()[:16]) # 3.11+: the same, built in
Output
Press Run (⌘ Enter) to see what happens.

Three things to notice:

  • Checking the first bytes (the "magic number") is how you tell a real PNG or PDF from a file someone renamed. Never trust the extension of an uploaded file.
  • Indexing bytes gives an int (header[1] is 80, the code for P), while slicing gives bytes. This surprises everyone once.
  • Binary files have no lines, so you stream them in fixed-size chunks with f.read(n). The while chunk := f.read(...) loop is the standard shape for hashing, copying or uploading a file of any size in constant memory.
Quick check
You need the SHA-256 of a 4 GB video upload without running out of memory. Which approach is right?
Need a nudge? A hint rules out a wrong answer.

pathlib: paths as objects

pathlib.Path is the modern way to work with file paths. Use it instead of gluing strings together with os.path.join. The / operator joins paths, and paths have handy methods.

Python
from pathlib import Path base = Path("project")data_dir = base / "data"data_dir.mkdir(parents=True, exist_ok=True) # like mkdir -p report = data_dir / "report.txt"report.write_text("line one\nline two\n", encoding="utf-8") # open, write, close print(report) # project/data/report.txtprint(report.name, report.stem, report.suffix, report.parent)print(report.exists(), report.is_file())print(report.read_text(encoding="utf-8").splitlines()) for path in sorted(base.rglob("*.txt")): # recursive search print("found:", path)
Output
Press Run (⌘ Enter) to see what happens.

read_text and write_text are perfect for small files. For big files, read line by line.

Match the pairs0/4 matched

Match each Path("data/sales.csv") attribute to its value.

Choose an item, then its match on the other side.

Large files: one line at a time

A file object is an iterator over lines. Looping over it reads one line at a time, so memory stays flat whether the file is 1 KB or 50 GB. f.read() and f.readlines() load everything at once.

Python
from pathlib import Path log = Path("server.log")log.write_text( "INFO boot\nERROR db down\nINFO retry\nERROR timeout\nINFO ok\n", encoding="utf-8",) errors = 0with log.open(encoding="utf-8") as f: for line_no, line in enumerate(f, start=1): # lazy: one line in memory line = line.rstrip("\n") if line.startswith("ERROR"): errors += 1 print(f"{line_no}: {line}")print("errors:", errors)
Output
Press Run (⌘ Enter) to see what happens.

Each line includes its trailing "\n", so strip it with rstrip("\n") (or strip() if you also want to drop spaces).

Predict the outputPython

What does this print?

from pathlib import Path
p = Path("t.txt")
p.write_text("a\nb\n\nc", encoding="utf-8")
with p.open(encoding="utf-8") as f:
  print(len(list(f)))
Need a nudge? Hints walk you through it.

JSON

JSON is the text format of the web: APIs send it, config files use it. Python's json module converts between JSON text and Python objects:

JSONPython
object {}dict
array []list
stringstr
numberint or float
true / falseTrue / False
nullNone
Python
import jsonfrom pathlib import Path order = {"id": 17, "items": ["pen", "pad"], "paid": True, "coupon": None} text = json.dumps(order) # Python -> JSON stringprint(text)print(json.dumps(order, indent=2, sort_keys=True)) back = json.loads(text) # JSON string -> Pythonprint(back["items"][0], back["coupon"] is None) path = Path("order.json")path.write_text(json.dumps(order), encoding="utf-8")print(json.loads(path.read_text(encoding="utf-8")) == order)
Output
Press Run (⌘ Enter) to see what happens.

The four names to remember: loads/dumps work with strings (the "s"), load/dump work with file objects. Some Python types have no JSON equivalent: tuples become lists, dict keys become strings, and datetime or set raise TypeError unless you convert them first.

Predict the outputPython

What does this print?

import json
data = {1: (2, 3)}
print(json.loads(json.dumps(data)))
Need a nudge? Hints walk you through it.

JSON Lines (.jsonl) puts one JSON object per line. It is popular for logs and data exports because you can process it line by line, append to it cheaply, and one bad line does not ruin the whole file.

Python
import json lines = '{"user": "ada", "ms": 120}\n{"user": "sam", "ms": 80}\nnot json\n{"user": "ada", "ms": 30}\n' total = {}for line in lines.splitlines(): try: event = json.loads(line) except json.JSONDecodeError: print("skipping bad line:", line) continue total[event["user"]] = total.get(event["user"], 0) + event["ms"]print(total)
Output
Press Run (⌘ Enter) to see what happens.

JSON edge cases that break production

The json module is simple until real data hits it. These are the cases that turn up in incident reports.

Python
import jsonimport uuidfrom datetime import datetime, timezonefrom decimal import Decimal order = { "id": uuid.UUID("12345678-1234-5678-1234-567812345678"), "placed_at": datetime(2026, 10, 22, 9, 30, tzinfo=timezone.utc), "total": Decimal("19.99"), "tags": {"gift"},} try: json.dumps(order)except TypeError as e: print("TypeError:", e) def to_json(value): """Called only for objects json cannot serialise itself.""" if isinstance(value, datetime): return value.isoformat() if isinstance(value, (uuid.UUID, Decimal)): return str(value) # strings keep Decimal exact if isinstance(value, set): return sorted(value) raise TypeError(f"cannot serialise {type(value).__name__}") print(json.dumps(order, default=to_json)) # NaN is not valid JSON, but Python writes it anyway unless told not toprint(json.dumps({"ratio": float("nan")}))try: json.dumps({"ratio": float("nan")}, allow_nan=False)except ValueError as e: print("ValueError:", e) # Unicode: escaped by default, readable with ensure_ascii=Falseprint(json.dumps({"name": "Zoë"}), json.dumps({"name": "Zoë"}, ensure_ascii=False)) # Floats vs money: parse_float keeps exact decimalsprint(json.loads('{"total": 0.1}')["total"] + 0.2)print(json.loads('{"total": 0.1}', parse_float=Decimal)["total"] + Decimal("0.2")) # Big ints are fine in Python, but JavaScript only keeps 2**53 exactlybig = 2**63 + 1print(json.loads(json.dumps(big)) == big, float(big) == big)
Output
Press Run (⌘ Enter) to see what happens.

What each part teaches:

  • default= is a function json calls for any object it cannot handle. Return something it can (a string, a list), or raise TypeError for anything you did not plan for, so a surprise type fails loudly instead of being silently stringified. Write datetimes as ISO 8601 with a time zone (Dates, Times and Time Zones explains why the offset matters). Send money as a string or integer cents, never a float.
  • NaN and Infinity are not JSON. Python writes them by default, and then a JavaScript JSON.parse or a strict parser in another service rejects the whole document. Pass allow_nan=False in anything that talks to other systems, so the bug surfaces where the NaN was created.
  • ensure_ascii=True (the default) escapes every non-ASCII character as ë. It is valid and safe, but unreadable in logs and files people open. Use ensure_ascii=False when you write to a UTF-8 file.
  • Big integers round-trip perfectly in Python, which has no size limit. JavaScript numbers are doubles and only represent integers exactly up to 2**53, so a 64-bit database ID silently changes in a browser. APIs send such IDs as strings. Python also refuses to parse integers longer than 4,300 digits by default, a protection against denial-of-service input.
  • sort_keys=True plus a fixed indent makes output deterministic, which matters for diffs, caches keyed on a hash of the JSON, and golden-file tests.

json.loads also accepts duplicate keys silently (the last one wins), and it parses an entire document into memory. For a multi-gigabyte JSON array, ask for JSON Lines instead, or use a streaming parser library.

Predict the outputPython

What does this print?

import json
print(json.dumps({"x": float("inf"), "ok": True}))
Need a nudge? Hints walk you through it.

CSV

For spreadsheet data use the csv module, never line.split(","): real CSV has quoted fields with commas inside them. csv.DictReader gives you each row as a dict keyed by the header. Open CSV files with newline="", as the docs require, so line endings are handled correctly.

Python
import csvfrom pathlib import Path path = Path("people.csv")with path.open("w", newline="", encoding="utf-8") as f: writer = csv.DictWriter(f, fieldnames=["name", "city", "age"]) writer.writeheader() writer.writerow({"name": "Ada", "city": "London", "age": 36}) writer.writerow({"name": "Sam", "city": "Austin, TX", "age": 29}) print(path.read_text(encoding="utf-8")) with path.open(newline="", encoding="utf-8") as f: for row in csv.DictReader(f): print(row["name"], "|", row["city"], "|", int(row["age"]) + 1)
Output
Press Run (⌘ Enter) to see what happens.

Notice that "Austin, TX" was quoted automatically, and that every value comes back as a string: convert numbers yourself.

Atomic writes: never leave a half-written file

Remember the quiz about "w" truncating the file the moment it opens. Combine that with a crash, a full disk or a killed container, and the next start reads a config file that ends mid-string. The fix is the atomic write: write the new content to a temporary file in the same folder, then rename it over the original with os.replace. A rename within one filesystem is a single step, so any reader sees either the old file or the new one, never half of each.

Atomic replace of settings.json
your codesettings.json.tmpsettings.jsoncreate and writecrash here?os.replace(tmp, path)

The original file is untouched. Readers still see the old settings.

1/3
Python
import jsonimport osimport tempfilefrom pathlib import Path def write_then_crash(f, data): text = json.dumps(data) f.write(text[:12]) # half the bytes reach the file... raise KeyboardInterrupt("power cut") # ...and the process dies def save_naive(path, data, crash=False): with open(path, "w", encoding="utf-8") as f: # the old content is gone at this line if crash: write_then_crash(f, data) json.dump(data, f) def save_atomic(path, data, crash=False): path = Path(path) fd, tmp = tempfile.mkstemp(dir=path.parent, suffix=".tmp") # same folder, unique name try: with os.fdopen(fd, "w", encoding="utf-8") as f: if crash: write_then_crash(f, data) json.dump(data, f) os.replace(tmp, path) # one rename: old file or new file, never half except BaseException: os.unlink(tmp) # clean up the partial temp file raise for save in (save_naive, save_atomic): settings = Path("settings.json") save(settings, {"theme": "dark", "retries": 3}) try: save(settings, {"theme": "light", "retries": 5}, crash=True) except KeyboardInterrupt: pass text = settings.read_text(encoding="utf-8") try: print(f"{save.__name__:12} after crash:", json.loads(text)) except json.JSONDecodeError: print(f"{save.__name__:12} after crash: CORRUPT", repr(text))print("temp files left:", list(Path(".").glob("*.tmp")))
Output
Press Run (⌘ Enter) to see what happens.

The temporary file must be in the same directory as the target: a rename across filesystems (say, from /tmp to a mounted volume) is not atomic, and os.replace raises OSError rather than attempt it. os.replace also overwrites the target on Windows, unlike os.rename. For data that must survive a power cut, not just a process crash, you also call f.flush() and os.fsync(f.fileno()) before the rename; Scripting and Automation has that full helper. Use atomic writes for config, state and cache files, and anything another process reads while you write.

Quick check
Why does an atomic write put the temporary file next to the target instead of in the system temp folder?
Need a nudge? A hint rules out a wrong answer.

tempfile and shutil

Two more standard-library modules round out everyday file work.

tempfile creates files and folders with unique, unguessable names that are cleaned up for you. tempfile.TemporaryDirectory() as a with block gives you a scratch folder that is deleted at the end, even after an error, which is ideal for unpacking an archive or building output before moving it into place. tempfile.NamedTemporaryFile() gives you a file with a real path you can hand to another program. tempfile.mkstemp(), used above, gives you a file you clean up yourself. Never build temp paths by hand like f"/tmp/{name}.txt": predictable names collide between runs and are a known attack on shared machines (Python Security Pitfalls covers why).

shutil does the jobs that pathlib does not: shutil.copy2(src, dst) copies a file with its timestamps, copytree and rmtree copy and delete whole folders, move works across filesystems by copying then deleting, copyfileobj streams one open file into another in chunks, and disk_usage tells you how much space is left before you write a big export.

import shutil
import tempfile
from pathlib import Path
 
with tempfile.TemporaryDirectory() as tmp:
    work = Path(tmp)
    shutil.unpack_archive("upload.zip", work)   # validate archives first: see Python Security Pitfalls
    for csv_path in work.rglob("*.csv"):
        shutil.copy2(csv_path, Path("inbox") / csv_path.name)
# the scratch folder and everything in it is gone here

Scripting and Automation goes further with shutil.make_archive, tree walks and bulk renames.

ChallengeMedium

Aggregate JSON Lines

You get the text of a JSON Lines log: one JSON object per line, like {"user": "ada", "ms": 120}. Write totals(text) that returns a dict mapping each user to the sum of their ms values.

Real logs are messy, so:

  • skip blank lines,
  • skip lines that are not valid JSON,
  • skip objects that are missing user or ms, or whose ms is not a number (int or float, but not bool).
text = '{"user": "ada", "ms": 120}\n{"user": "sam", "ms": 80}\nnot json\n{"user": "ada", "ms": 30}'
totals(text)   # {"ada": 150, "sam": 80}
Python
import json def totals(text: str) -> dict[str, float]: # Parse each line with json.loads inside a try block. pass
ChallengeEasy

Count words in a file

Write word_counts(path) that reads a UTF-8 text file line by line and returns a dict of how many times each word appears.

  • A word is a run of letters, digits or apostrophes. Use re.findall(r"[\w']+", line).
  • Count case-insensitively: "The" and "the" are the same word (store it lowercase).
  • path may be a str or a pathlib.Path.
# notes.txt contains:
# The cat sat.
# The dog didn't.
word_counts("notes.txt")
# {"the": 2, "cat": 1, "sat": 1, "dog": 1, "didn't": 1}
Python
import refrom pathlib import Path def word_counts(path: str | Path) -> dict[str, int]: # Open the file with encoding="utf-8" and loop over its lines. pass
Key terms
encoding
The rule mapping bytes to characters. Use UTF-8 and pass encoding="utf-8" explicitly.
pathlib.Path
An object representing a file path, joined with /, with methods like read_text and rglob.
streaming
Processing a file line by line (for line in f) so memory use stays constant.
json.loads / dumps
Convert a JSON string to Python objects and back. load/dump do the same with files.
JSON Lines
One JSON document per line, easy to append to and to process line by line.
csv.DictReader
Reads CSV rows as dicts keyed by the header row, handling quoting correctly.
bytes
An immutable sequence of raw byte values, what binary-mode files read and write.
atomic write
Writing to a temp file in the same folder, then os.replace over the target, so readers never see a partial file.
default= (json)
A function json.dumps calls for types it cannot serialise, such as datetime, Decimal or UUID.