07. Files and data formats — Cheat sheet
The essentials of module 07 on one page. Every runnable block on this page is checked against its output. The blocks run in order and share their variables.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Example |
|---|---|---|
| build a path | Path and / |
Path("data") / "reports" / "2024-01.csv" |
| get the file name, stem, extension, folder | .name, .stem, .suffix, .parent |
p.stem → '2024-01' |
| change the extension | p.with_suffix(".json") |
data/x.csv → data/x.json |
| check that a file exists | p.exists(), p.is_file(), p.is_dir() |
Path("data").is_dir() |
| get a file size | p.stat().st_size |
bytes, an int |
| create an output folder | p.mkdir(parents=True, exist_ok=True) |
Path("output").mkdir(...) |
| read a small text file | p.read_text(encoding="utf-8") |
one str |
| write a small text file | p.write_text(text, encoding="utf-8") |
replaces the file |
| read a large file line by line | with open(p, encoding="utf-8") as f: for line in f: |
constant memory |
| append to a log | open(p, "a", encoding="utf-8") |
keeps old lines |
| refuse to overwrite | open(p, "x", ...) |
FileExistsError if it exists |
| read bytes | p.read_bytes() or open(p, "rb") |
bytes |
| read an Excel “CSV UTF-8” file | encoding="utf-8-sig" |
removes the BOM |
| read a legacy file | encoding="latin-1" or "cp1252" |
old exports |
| read a CSV by column name | csv.DictReader(f) |
row["revenue"] |
| write a CSV with a fixed column order | csv.DictWriter(f, fieldnames=[...]) |
writeheader(), writerows() |
| read a semicolon or tab file | csv.reader(f, delimiter=";") / "\t" |
European Excel, TSV |
| load / save JSON | json.load(f) / json.dump(obj, f, indent=2) |
config files |
| parse / build a JSON string | json.loads(s) / json.dumps(obj) |
API bodies |
| save a date in JSON | d.isoformat(); read back date.fromisoformat(s) |
"2024-05-02" |
| append records | JSON Lines: f.write(json.dumps(rec) + "\n") |
.jsonl |
| save any Python object (trusted use only) | pickle.dump(obj, f) with "wb" |
caches, models |
| list the CSV files in a folder | sorted(folder.glob("*.csv")) |
always sort |
| find files in all subfolders | sorted(folder.rglob("*.json")) |
recursive |
| walk a tree folder by folder | folder.walk() (3.12+) or os.walk(folder) |
inventories |
| delete a file if it exists | p.unlink(missing_ok=True) |
reruns |
| print a portable path | p.as_posix() |
forward slashes everywhere |
Paths with pathlib
Section titled “Paths with pathlib”from pathlib import Path
p = Path("data") / "reports" / "2024-04.csv"print(p.name, p.stem, p.suffix) # name, name without suffix, extensionprint(p.parent.as_posix(), p.parts[-2]) # containing folderprint(p.with_suffix(".json").as_posix(), p.with_name("april.csv").as_posix())print(p.exists(), p.is_file(), p.is_dir(), p.stat().st_size)print(Path("data/products.csv").suffix == ".csv", Path("archive.tar.gz").suffixes)2024-04.csv 2024-04 .csvdata/reports reportsdata/reports/2024-04.json data/reports/april.csvTrue True False 3146True ['.tar', '.gz']| Attribute or method | Returns | Note |
|---|---|---|
p.name / p.stem / p.suffix |
str |
suffixes lists all of them: ['.tar', '.gz'] |
p.parent / p.parents |
Path / sequence |
p.parents[1] is two levels up |
p.parts |
tuple of str |
('data', 'reports', '2024-04.csv') |
p.with_name(n) / p.with_stem(s) / p.with_suffix(s) |
new Path |
nothing changes on disk |
p.exists() / p.is_file() / p.is_dir() |
bool |
False for a missing path, no error |
p.stat().st_size |
int bytes |
st_mtime: last change, in seconds |
p.mkdir(parents=True, exist_ok=True) |
None |
safe to call on every run |
p.unlink(missing_ok=True) |
None |
delete a file |
p.rename(t) / p.replace(t) |
new Path |
replace overwrites t |
p.relative_to(base) |
Path |
Path("data/logs/app.log").relative_to("data") → logs/app.log |
p.resolve() / Path.cwd() |
absolute Path |
machine-specific: do not print in reports |
p.as_posix() |
str with / |
stable output on Windows |
Reading and writing text
Section titled “Reading and writing text”out = Path("output")out.mkdir(parents=True, exist_ok=True)notes = out / "notes.txt"notes.write_text("line 1\n", encoding="utf-8") # whole file at once (replaces it)with open(notes, "a", encoding="utf-8") as f: # append mode f.write("line 2\n") # write() adds no line break print("line 3", file=f) # print() adds onewith open(notes, encoding="utf-8") as f: header = f.readline() # one line, with "\n" rest = [line.rstrip("\n") for line in f] # the remaining lines, streamedprint(repr(header), rest, f.closed)'line 1\n' ['line 2', 'line 3'] True| Pattern | Use |
|---|---|
for line in f: |
default: one line at a time, any file size |
line.rstrip("\n") / line.strip() |
drop the line break / also the spaces |
f.read() / p.read_text() |
small files only |
f.read(65536) in a while loop |
binary files in chunks (checksums, copies) |
text.splitlines() |
lines without \n; also handles \r\n |
with open(a) as src, open(b, "w") as dst: |
read one file while you write another |
File modes
Section titled “File modes”| Mode | Reads | Writes | Existing file | Missing file |
|---|---|---|---|---|
"r" (default) |
yes | no | read from start | FileNotFoundError |
"w" |
no | yes | emptied | created |
"a" |
no | at the end | kept | created |
"x" |
no | yes | FileExistsError |
created |
"r+" |
yes | yes | kept | FileNotFoundError |
"rb", "wb", "ab", "xb" |
binary versions: bytes in, bytes out, no encoding |
with open(notes, "x", encoding="utf-8") as f: f.write("never written")FileExistsError: [Errno 17] File exists: 'output/notes.txt'Line endings
Section titled “Line endings”| Fact | Detail |
|---|---|
| LF / CRLF | \n (Linux, macOS) / \r\n (Windows, the CSV standard) |
| Text mode reading | \r\n and \n both arrive as \n (universal newlines) |
| Text mode writing | \n becomes the OS line ending; newline="\n" forces LF |
newline="" |
no translation: required for every CSV file you open |
csv writer default |
ends each row with \r\n; lineterminator="\n" changes it |
Text and binary, encodings
Section titled “Text and binary, encodings”city = "Köln"print(city.encode("utf-8"), city.encode("latin-1")) # str -> bytesprint(b"K\xc3\xb6ln".decode("utf-8"), b"K\xc3\xb6ln".decode("latin-1")) # mojibakeprint(b"Caf\xe9".decode("utf-8", errors="replace")) # inspect damageraw = Path("data/legacy_latin1.csv").read_bytes()print(raw[:20], raw.decode("latin-1").splitlines()[1])b'K\xc3\xb6ln' b'K\xf6ln'Köln KölnCaf�b'supplier_id,supplier' SUP01,Café Müller GmbH,Köln,Germany,2015| Encoding | Bytes per character | Use |
|---|---|---|
"utf-8" |
1–4 | write every new file in it |
"utf-8-sig" |
as UTF-8, plus a 3-byte BOM | read Excel “CSV UTF-8”; safe without a BOM too |
"latin-1" / "iso-8859-1" |
1 | old Western European exports; never raises |
"cp1252" |
1 | Windows legacy files; like Latin-1 plus €, “, ” |
"ascii" |
1 | only 128 characters; fails on é |
errors= |
On a bad byte |
|---|---|
"strict" (default) |
UnicodeDecodeError |
"replace" |
�; good for inspecting a damaged file |
"ignore" |
drops it silently: avoid, it hides a wrong encoding |
"backslashreplace" |
shows \xe9; good for logs |
| First bytes | Format |
|---|---|
b"\xef\xbb\xbf" |
UTF-8 with BOM |
b"PK\x03\x04" |
ZIP: .xlsx, .docx, .zip |
b"PAR1" |
Parquet |
b"SQLite format 3\x00" |
SQLite database |
b"\x80" then a protocol byte |
pickle |
b"\x89PNG" |
PNG image |
import csv
with open("data/stores.csv", encoding="utf-8", newline="") as f: reader = csv.DictReader(f) # one dict per row, keyed by the header columns = reader.fieldnames stores = [row for row in reader if row["region"] == "West"]print(columns)print([(s["store_id"], int(s["size_sqm"])) for s in stores]) # values are str
with open(out / "west.csv", "w", encoding="utf-8", newline="") as f: writer = csv.DictWriter(f, fieldnames=["store_id", "city"], extrasaction="ignore") writer.writeheader() writer.writerows(stores) # extra keys are ignoredprint((out / "west.csv").read_text(encoding="utf-8").splitlines())['store_id', 'city', 'region', 'size_sqm', 'opened'][('S10', 2480), ('S11', 1890), ('S12', 1350)]['store_id,city', 'S10,Seattle', 'S11,San Francisco', 'S12,Denver']| Need | Code |
|---|---|
| rows as lists | csv.reader(f); header with next(reader) |
| rows as dicts | csv.DictReader(f) |
| a file without a header | csv.DictReader(f, fieldnames=[...]) |
| write lists / dicts | csv.writer(f).writerow(list) / csv.DictWriter(f, fieldnames) |
| other delimiter | delimiter=";", delimiter="\t" |
| quote every field | csv.writer(f, quoting=csv.QUOTE_ALL) |
| dicts with extra keys | DictWriter(..., extrasaction="ignore") |
| missing keys in a dict | DictWriter(..., restval="") |
| count rows correctly | count csv.reader rows, not lines: quoted fields may hold line breaks |
JSON and JSON Lines
Section titled “JSON and JSON Lines”import json
with open("data/config.json", encoding="utf-8") as f: config = json.load(f) # dictcompress = config.get("export", {}).get("compress", False) # optional, with defaultprint(config["thresholds"]["max_quantity"], compress)text = json.dumps({"ok": True, "missing": None, "pair": (1, 2)}, sort_keys=True)print(text, json.loads(text)["pair"])print(json.dumps({"city": "Köln"}), json.dumps({"city": "Köln"}, ensure_ascii=False))
with open(out / "events.jsonl", "w", encoding="utf-8") as f: for name in ["2024-01.csv", "2024-02.csv"]: f.write(json.dumps({"file": name, "status": "ok"}) + "\n") # one per linewith open(out / "events.jsonl", encoding="utf-8") as f: print([json.loads(line)["file"] for line in f])50 False{"missing": null, "ok": true, "pair": [1, 2]} [1, 2]{"city": "K\u00f6ln"} {"city": "Köln"}['2024-01.csv', '2024-02.csv']| Python → JSON | JSON → Python |
|---|---|
dict → object (keys become str) |
object → dict |
list, tuple → array |
array → list |
str, int, float → string, number |
string, number → str, int/float |
True/False/None → true/false/null |
true/false/null → True/False/None |
set, date, bytes → TypeError |
(no dates: parse strings yourself) |
| Argument | Effect |
|---|---|
indent=2 |
readable, multi-line output |
sort_keys=True |
fixed key order: stable diffs |
ensure_ascii=False |
write Köln, not K\u00f6ln (keep encoding="utf-8") |
default=str |
convert unknown types (dates) with str() |
from datetime import date
print(json.dumps({"run_date": date(2024, 5, 2)}, default=str))print(json.dumps({"classes": {0, 1}})){"run_date": "2024-05-02"}TypeError: Object of type set is not JSON serializablepickle
Section titled “pickle”import pickle
state = {"rates": {"one-year": 0.088}, "classes": {0, 1}, "shape": (5000, 15)}with open(out / "state.pkl", "wb") as f: # binary mode, no encoding pickle.dump(state, f)with open(out / "state.pkl", "rb") as f: print(pickle.load(f) == state) # exact round trip of Python typesTrue| Rule | Why |
|---|---|
Never pickle.load() a file you did not create |
loading runs code chosen by the file’s author |
Use "wb" / "rb" |
a pickle is bytes |
| Do not archive with pickle | other Python or library versions may not load it |
| Exchange data as CSV, JSON or Parquet | data-only formats, readable by any language |
ML models: joblib (module 34) |
same risk, better for large NumPy arrays |
Directories
Section titled “Directories”reports = sorted(Path("data/reports").glob("*.csv")) # always sortprint(len(reports), reports[0].as_posix(), reports[-1].name)print([p.name for p in sorted(Path("data").glob("*.json"))])print(sorted(p.relative_to("data").as_posix() for p in Path("data").rglob("*.log")))for dirpath, dirnames, filenames in Path("data").walk(): dirnames.sort() # fix the visiting order if dirpath.name == "reports": print(dirpath.as_posix(), len(filenames), "files")6 data/reports/2024-01.csv 2024-06.csv['config.json', 'customers.json']['logs/app.log']data/reports 6 files| Pattern | Matches |
|---|---|
*.csv |
any name ending in .csv, in this folder |
2024-0?.csv |
2024-01.csv … 2024-09.csv |
2024-0[1-3].csv |
the first three months |
**/*.json (with glob) or rglob("*.json") |
every .json in all subfolders |
File errors
Section titled “File errors”| Exception | Cause | Fix |
|---|---|---|
FileNotFoundError |
wrong path or wrong working directory | cd to the project folder; check p.exists() |
FileExistsError |
mode "x", mkdir() without exist_ok=True |
choose "w"/"a", or keep the old file |
IsADirectoryError |
open() on a folder |
open a file inside it |
PermissionError |
no rights; file locked by Excel on Windows | close the program; check permissions |
UnicodeDecodeError |
wrong encoding | find the real one; read_bytes() to inspect |
json.JSONDecodeError |
invalid JSON, or two objects in one file | validate; use JSON Lines for records |
ValueError: I/O operation on closed file. |
file used after its with block |
work inside the block |
TypeError: write() argument must be str, not bytes |
binary data in a text-mode file | "wb" |
try: text = Path("data/sales_2025.csv").read_text(encoding="utf-8")except FileNotFoundError as error: print("missing:", error.filename)except OSError as error: # any other file-system problem print("cannot read:", error)missing: data/sales_2025.csvChoosing a format
Section titled “Choosing a format”| Data | Format | Why |
|---|---|---|
| a table for people and Excel | CSV | universal; open with newline="" |
| settings, API payloads, nested records | JSON | types, nesting, readable |
| logs, events, streamed records | JSON Lines | append and stream line by line |
| big typed tables between pipeline steps | Parquet (module 24) | fast, compressed, keeps dtypes |
| your own short-lived Python objects | pickle | exact types; never from strangers |
| plain readings, one per line | .txt |
simplest; parse with float() |
Gotchas
Section titled “Gotchas”- Relative paths start at the working directory, not at the script. Run scripts from the project folder.
- Always pass
encoding=in text mode. The default depends on the OS and the Python version. "w"empties the file the moment it opens it, even if nothing is written afterwards.f.write()adds no line break.print(..., file=f)does.- Open every CSV with
newline="", or Windows gets an empty line after each row. - The
csvwriter ends rows with\r\n. File sizes differ from a\nsource; content does not. split(",")breaks on quoted commas, such as"January 7, 2023". Use thecsvmodule.- Read columns by name with
DictReader. Another column order in one file then does no harm. - Every CSV value is a
str. Convert before you compare or add:"79.99" > "129.95"isTrue. - JSON keys become strings, tuples become lists, and dates and sets raise
TypeError. json.dumps(float("nan"))writesNaN, which is not valid JSON; other tools reject the file. Convert NaN toNonefirst, or passallow_nan=Falseto fail early.- Two JSON objects in one file is invalid JSON. Use JSON Lines for appended records.
pickle.load()runs code. Load only pickles you created.glob(),rglob(),iterdir()andwalk()return files in an OS-dependent order. Sort them.- Never write results into
data/. A folder pipeline would read its own output on the next run. - A file used after its
withblock is closed:ValueError: I/O operation on closed file. - Excel “CSV UTF-8” starts with a BOM. Read it with
"utf-8-sig", or the first column name becomes'\ufeffstore_id'.