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.
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.
Press Run (⌘ Enter) to see what happens.| Mode | Meaning |
|---|---|
"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.
report.txt contains 100 lines. You run open("report.txt", "w") and then your program crashes before writing. What is in the file now?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.
ë is two bytes in UTF-8: \xc3\xab. Decoding with the right encoding turns bytes into characters.
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.
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.
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
bytesgives anint(header[1]is80, the code forP), while slicing givesbytes. This surprises everyone once. - Binary files have no lines, so you stream them in fixed-size chunks with
f.read(n). Thewhile chunk := f.read(...)loop is the standard shape for hashing, copying or uploading a file of any size in constant memory.
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.
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 each Path("data/sales.csv") attribute to its value.
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.
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).
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)))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:
| JSON | Python |
|---|---|
object {} | dict |
array [] | list |
| string | str |
| number | int or float |
true / false | True / False |
null | None |
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.
What does this print?
import json
data = {1: (2, 3)}
print(json.loads(json.dumps(data)))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.
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.
Press Run (⌘ Enter) to see what happens.What each part teaches:
default=is a functionjsoncalls for any object it cannot handle. Return something it can (a string, a list), or raiseTypeErrorfor 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.NaNandInfinityare not JSON. Python writes them by default, and then a JavaScriptJSON.parseor a strict parser in another service rejects the whole document. Passallow_nan=Falsein anything that talks to other systems, so the bug surfaces where theNaNwas 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. Useensure_ascii=Falsewhen 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=Trueplus a fixedindentmakes 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.
What does this print?
import json
print(json.dumps({"x": float("inf"), "ok": True}))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.
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.
The original file is untouched. Readers still see the old settings.
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.
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 hereScripting and Automation goes further with shutil.make_archive, tree walks and bulk renames.
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
userorms, or whosemsis not a number (intorfloat, but notbool).
text = '{"user": "ada", "ms": 120}\n{"user": "sam", "ms": 80}\nnot json\n{"user": "ada", "ms": 30}'
totals(text) # {"ada": 150, "sam": 80}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). pathmay be astror apathlib.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}- 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 likeread_textandrglob. - 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/dumpdo 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.replaceover the target, so readers never see a partial file. - default= (json)
- A function
json.dumpscalls for types it cannot serialise, such asdatetime,DecimalorUUID.