A large share of operations work is reading files and writing others: parse a log, update a JSON config, produce a CSV report. Python's standard library covers all of it: pathlib for paths, open() with with and an explicit encoding, re for patterns, csv and json for structured data. This lesson builds one nightly report from an access log, and shows the two file bugs that cause outages: reading a 20 GB file into memory, and rewriting a config file in place so a crash leaves it half written.
Difficulty: Intermediate · Know this first: Lesson 34, Lesson 29
This bar adds up minutes for the nightly job, including what its failures cost. It is a worked example, not a measurement. The streaming and atomic-write hops turn a script into a safe job.
Set the log size and how the script reads it. Reading everything needs the file in memory, and splitting it into a list of lines needs more.
Out of memory: reading 20 GB at once needs far more than 16 GB
Three questions. No score is saved anywhere — this is just you against the material.
File handling grows in four levels: reading and writing, parsing, robust jobs, and data at scale.
At the basic level you can read, write, and find files.
with open(p, encoding="utf-8") as f:; modes r, w, a, x.Path: / to join, .read_text() for small files, .glob(), .exists().for line in f: and line.rstrip("\n").Where it breaks: forgetting the encoding, so the same script reads a file differently on Windows and Linux.
Try it: Basic
Which mode adds to the end of an existing file without erasing it?
Now do it: Append a line to a file twice and read it back.
At the intermediate level you turn text into data.
re.compile with named groups; match, search, findall, sub.csv.DictReader and DictWriter with newline="".json.load/dump, indent, sort_keys, default=str.Try it: Intermediate
Why write regex patterns as r"\d+\s" instead of "\d+\s"?
Now do it: Compare len("\b") with len(r"\b").
At the advanced level file jobs are safe to run unattended.
gzip.open for compressed logs.fsync, os.replace.fcntl.flock), and counts of skipped lines.Try it: Advanced
Why must the temporary file be in the same directory as the target before os.replace()?
Now do it: Write an atomic_write_json(path, data) helper and use it in one script.
At the master level the right tool handles the size.
multiprocessing.Trade-off: a custom streaming parser is small and dependency-free; a query engine is faster to write analyses with and adds a dependency and its memory needs.
Try it: Master
Logs are parsed with fragile regex every night. What removes the problem at the source?
Now do it: Find one log you parse with regex and check whether the app can log JSON.
The nightly job: stream a log, count, write a CSV, and update a JSON file atomically. Standard library only.
import csv, json, os, re, sys, tempfile
from collections import Counter
from pathlib import Path
LINE = re.compile(r'(?P<ip>\S+) \S+ \S+ \[[^\]]+\] "(?P<method>[A-Z]+) (?P<path>\S+)[^"]*" (?P<status>\d{3})')
def atomic_write_json(path, data):
path = Path(path)
with tempfile.NamedTemporaryFile("w", dir=path.parent, delete=False, encoding="utf-8") as tmp:
json.dump(data, tmp, indent=2, sort_keys=True)
tmp.flush()
os.fsync(tmp.fileno())
os.replace(tmp.name, path) # readers see old or new, never half
def main(log_path, out_dir):
status, paths, skipped, total = Counter(), Counter(), 0, 0
with open(log_path, encoding="utf-8", errors="replace") as f:
for line in f: # streams: constant memory
total += 1
m = LINE.match(line)
if not m:
skipped += 1
continue
status[m["status"]] += 1
paths[m["path"]] += 1
if total == 0:
sys.exit("no lines read")
out = Path(out_dir); out.mkdir(parents=True, exist_ok=True)
with open(out / "report.csv", "w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=["path", "hits"])
w.writeheader()
w.writerows({"path": p, "hits": n} for p, n in paths.most_common(20))
atomic_write_json(out / "status.json", dict(status))
print(f"{total} lines, {skipped} skipped", file=sys.stderr)
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2])
This is a composite of a failure pattern that keeps repeating; the details are illustrative. A config updater took a service down by crashing at the wrong moment.
All config writers use an atomic write helper, the gateway validates config before reloading and keeps the last good version, and the job takes a lock so two runs cannot overlap.
Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.
Type each one, read what it prints, and compare it with the note above it.
Make a sample access log to practise on.
python3 -c "import random; random.seed(1); [print(f'10.0.0.{random.randint(1, 9)} - - [25/Nov/2026:10:00:{s:02d} +0000] \"GET /{random.choice(['', 'api', 'login'])} HTTP/1.1\" {random.choice([200, 200, 200, 404, 500])} 512') for s in range(60)]" > access.log; head -3 access.log; wc -l access.logStreaming memory stays flat; reading everything does not.
/usr/bin/time -f "%M KB peak" python3 -c "sum(1 for _ in open('access.log'))"; /usr/bin/time -f "%M KB peak" python3 -c "len(open('access.log').read())"Opening with "w" empties a file immediately.
echo "important" > cfg.txt; python3 -c "f = open('cfg.txt', 'w'); raise SystemExit('crashed before writing')"; wc -c cfg.txtCheck JSON is valid before a service reads it, then clean up.
echo '{"rate": 100}' > ok.json; echo '{"rate": 10' > bad.json; for f in ok.json bad.json; do python3 -m json.tool "$f" >/dev/null 2>&1 && echo "$f valid" || echo "$f INVALID"; done; rm -f access.log cfg.txt ok.json bad.jsonlog_report.pyThis program streams an access log through a compiled regex, counts statuses and paths, writes a CSV, and writes a JSON file atomically with a temporary file and os.replace. Save it as log_report.py, then run it.
# log_report.py
import csv, io, json, os, re, tempfile
from collections import Counter
LOG = """10.0.0.4 - - [25/Nov/2026:10:00:01 +0000] "GET /api/orders HTTP/1.1" 200 512
10.0.0.9 - - [25/Nov/2026:10:00:02 +0000] "POST /login HTTP/1.1" 401 88
garbage line from a crashed writer
10.0.0.4 - - [25/Nov/2026:10:00:03 +0000] "GET /api/orders HTTP/1.1" 500 0
10.0.0.7 - - [25/Nov/2026:10:00:04 +0000] "GET /api/users,admins HTTP/1.1" 200 1024"""
LINE = re.compile(r'(?P<ip>\S+) \S+ \S+ \[[^\]]+\] "(?P<method>[A-Z]+) (?P<path>\S+)[^"]*" (?P<status>\d{3})')
status, paths, skipped = Counter(), Counter(), 0
for line in io.StringIO(LOG): # a file object streams the same way
m = LINE.match(line)
if not m:
skipped += 1
continue
status[m["status"]] += 1
paths[m["path"]] += 1
out = io.StringIO()
w = csv.DictWriter(out, fieldnames=["path", "hits"], lineterminator="\n")
w.writeheader()
w.writerows({"path": p, "hits": n} for p, n in sorted(paths.items()))
print(out.getvalue().strip())
d = tempfile.mkdtemp()
target = os.path.join(d, "status.json")
with tempfile.NamedTemporaryFile("w", dir=d, delete=False, encoding="utf-8") as tmp:
json.dump(dict(sorted(status.items())), tmp, sort_keys=True)
tmp.flush(); os.fsync(tmp.fileno())
os.replace(tmp.name, target)
print("status.json:", open(target, encoding="utf-8").read(), "| skipped lines:", skipped)
Run it, and you should see this output:
$ python3 log_report.py
path,hits
/api/orders,2
"/api/users,admins",1
/login,1
status.json: {"200": 2, "401": 1, "500": 1} | skipped lines: 1
The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/python-files-json-csv-and-regex-for-ops && cd ~/labs/python-files-json-csv-and-regex-for-ops) and save this as lab.sh.
#!/usr/bin/env bash
# The Linux steps of "Python for Files: Paths, JSON, CSV, and Regex", as one script (save it as lab.sh).
#
# ./lab.sh run every step, in order
# ./lab.sh 2 4 run only steps 2 and 4
# ./lab.sh --list list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.
STEPS=(
'Make a sample access log to practise on.'
'Streaming memory stays flat; reading everything does not.'
'Opening with "w" empties a file immediately.'
'Check JSON is valid before a service reads it, then clean up.'
)
step_1() {
python3 -c "import random; random.seed(1); [print(f'10.0.0.{random.randint(1, 9)} - - [25/Nov/2026:10:00:{s:02d} +0000] \"GET /{random.choice(['', 'api', 'login'])} HTTP/1.1\" {random.choice([200, 200, 200, 404, 500])} 512') for s in range(60)]" > access.log; head -3 access.log; wc -l access.log
}
step_2() {
/usr/bin/time -f "%M KB peak" python3 -c "sum(1 for _ in open('access.log'))"; /usr/bin/time -f "%M KB peak" python3 -c "len(open('access.log').read())"
}
step_3() {
echo "important" > cfg.txt; python3 -c "f = open('cfg.txt', 'w'); raise SystemExit('crashed before writing')"; wc -c cfg.txt
}
step_4() {
echo '{"rate": 100}' > ok.json; echo '{"rate": 10' > bad.json; for f in ok.json bad.json; do python3 -m json.tool "$f" >/dev/null 2>&1 && echo "$f valid" || echo "$f INVALID"; done; rm -f access.log cfg.txt ok.json bad.json
}
# print a step that has to be run by hand, instead of running it
by_hand() {
echo " (run this one yourself: $1)"
sed 's/^/ /'
}
RESULTS=()
run_step() {
local n=$1 start=$SECONDS code
printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
"step_$n"
code=$?
RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}
summary() {
echo
echo "== summary"
local r
for r in "${RESULTS[@]}"; do echo " $r"; done
}
case "${1:-}" in
-h|--help) sed -n '2,6p' "$0"; exit 0 ;;
--list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac
[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
echo "there is no step '$n'; try --list" >&2
exit 2
fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done
Then make it executable and run it:
chmod +x lab.sh ./lab.sh --list # the steps ./lab.sh # every step, then a summary of exit codes and times ./lab.sh 2 3 # only steps 2 and 3
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
wc, head, rm, echo, Pipes, Redirection, Loops, If...Else.Write a job that reads a day of gzip-compressed nginx logs from 30 servers and produces a per-endpoint latency report and an updated JSON file of slow endpoints for the gateway.
How do you keep memory flat across 300 GB of input? What happens to lines that do not parse? How is the gateway's JSON written so a crash cannot break it? How do you stop two runs overlapping?
Say 10 GB per server per day, compressed 10 to 1, and a gateway that reloads its file every minute.
gzip.open in a streaming loop per file, one process per server with multiprocessing; a compiled regex with named groups and a skipped-line counter; Counters and running sums for latency per endpoint; csv.DictWriter for the report; an atomic JSON write in the gateway's directory; fcntl.flock on a lock file; exit non-zero if too many lines are skipped.
Parallel processing cuts the run time and multiplies memory and CPU use. A strict parser catches format changes quickly and may fail the whole job; a lenient one keeps going and needs a threshold on skipped lines to notice.