Skip to content

Files, paths and formats

Working with the file system and the common file formats: pathlib for paths, open() modes and encodings, csv, json, pickle, tomllib, shutil, tempfile and folder walking. The examples read the course datasets in data/ and write to output/. Every runnable block is checked against its output.

I want to… Use… Example
build a path Path and / Path("data") / "sales.csv"
get the file name, stem, extension .name, .stem, .suffix Path("a/b.csv").stem → 'b'
get the parent folder .parent Path("data/api/x.json").parent
change the extension .with_suffix(".parquet")
check that a file exists p.exists(), p.is_file(), p.is_dir()
create a folder and its parents p.mkdir(parents=True, exist_ok=True)
read a whole small text file p.read_text(encoding="utf-8")
write a whole text file p.write_text(text, encoding="utf-8") overwrites
read a file line by line with open(p, encoding="utf-8") as f: for line in f: constant memory
append to a file open(p, "a", encoding="utf-8")
create a file only if it does not exist open(p, "x") FileExistsError otherwise
read binary data p.read_bytes() or open(p, "rb") images, pickles, unknown encodings
list the files of a folder sorted(p.iterdir())
find files by pattern p.glob("*.csv"), p.rglob("*.json") rglob is recursive
walk a folder tree Path.walk() (3.12+) or os.walk()
file size, modification time p.stat().st_size, .st_mtime
delete a file p.unlink(missing_ok=True)
delete a folder tree shutil.rmtree(p) no undo
copy or move shutil.copy2(src, dst), shutil.move(src, dst) copytree for folders
rename, replacing the target p.replace(target) atomic on the same drive
read CSV rows as dicts csv.DictReader(f) open with newline=""
write CSV from dicts csv.DictWriter(f, fieldnames=...) writeheader(), writerows()
read JSON json.load(f) / json.loads(text)
write JSON readably json.dump(obj, f, indent=2, ensure_ascii=False)
serialize dates and other types to JSON default=str json.dumps(obj, default=str)
read and write JSON Lines one json.loads(line) per line logs, streams
read a TOML config tomllib.load(f) (binary mode) pyproject.toml
save any Python object (trusted use only) pickle.dump(obj, f) never load untrusted pickles
get a temporary folder tempfile.TemporaryDirectory() deleted after with
read a gzip file gzip.open(p, "rt", encoding="utf-8")
open a zip archive zipfile.ZipFile(p) .namelist(), .open(name)
make an archive of a folder shutil.make_archive("out", "zip", folder)
find a program on the PATH shutil.which("git") None if missing
get the script’s own folder Path(__file__).resolve().parent not the working folder
expand ~ Path("~/data").expanduser()
Attribute or method p = Path("data/api/products_page_1.json") Note
p.name 'products_page_1.json'
p.stem, p.suffix 'products_page_1', '.json'
p.suffixes ['.json'] ['.tar', '.gz'] for archives
p.parent, p.parents[1] data/api, data
p.parts ('data', 'api', 'products_page_1.json')
p.with_suffix(".csv") data/api/products_page_1.csv
p.with_name("x.json"), p.with_stem("x") data/api/x.json with_stem is 3.9+
p.is_absolute() False
p.resolve() absolute path, symlinks resolved
p.relative_to("data") api/products_page_1.json ValueError if not inside
p.is_relative_to("data") True
p.match("*.json"), p.full_match("data/**/*.json") True full_match is 3.13+
p.exists(), p.is_file(), p.is_dir()
p.stat().st_size size in bytes
p.read_text(), p.write_text(), p.read_bytes(), p.write_bytes() whole-file I/O pass encoding= for text
p.open(mode, encoding=) same as open(p, ...)
p.iterdir(), p.glob(pat), p.rglob(pat), p.walk() iterate a folder order is arbitrary: sort
p.mkdir(parents=True, exist_ok=True), p.touch() create
p.unlink(missing_ok=True), p.rmdir() delete a file / an empty folder
p.rename(t), p.replace(t) move or rename replace overwrites t
Path.cwd(), Path.home() working folder, home folder
Path("~").expanduser() expand ~
from pathlib import Path
p = Path("data") / "api" / "products_page_1.json"
print(p, p.name, p.stem, p.suffix, p.parent)
print(p.parts, p.parents[1], p.suffixes)
print(p.with_suffix(".csv"), p.with_stem("page1"), p.relative_to("data"))
print(p.exists(), p.is_file(), p.parent.is_dir(), p.stat().st_size > 0)
print(sorted(f.name for f in Path("data/reports").glob("*.csv"))[:3])
print(sorted(str(f) for f in Path("data").rglob("*.log")), p.as_posix())
Output
data/api/products_page_1.json products_page_1.json products_page_1 .json data/api
('data', 'api', 'products_page_1.json') data ['.json']
data/api/products_page_1.csv data/api/page1.json api/products_page_1.json
True True True True
['2024-01.csv', '2024-02.csv', '2024-03.csv']
['data/logs/app.log'] data/api/products_page_1.json
Legacy os.path pathlib
os.path.join(a, b) Path(a) / b
os.path.exists(p), isfile, isdir p.exists(), p.is_file(), p.is_dir()
os.path.basename(p) p.name
os.path.dirname(p) p.parent
os.path.splitext(p) (p.stem, p.suffix); p.with_suffix(".csv") to change it
os.path.getsize(p) p.stat().st_size
os.path.expanduser("~/x") Path("~/x").expanduser()
os.path.abspath(p) p.resolve() (also resolves symlinks)

Atomic write: write a temporary file in the same folder, then replace the target in one step. A crash never leaves a half-written file.

atomic write
tmp = target.with_name(target.name + ".tmp") # same folder, same file system
tmp.write_text(text, encoding="utf-8")
tmp.replace(target) # atomic rename; overwrites target
Mode Read Write Creates Truncates Position Missing file
"r" (default) yes start FileNotFoundError
"w" yes yes yes start created
"a" yes yes end created
"x" yes yes start created; FileExistsError if it exists
"r+" yes yes start FileNotFoundError
"w+" yes yes yes yes start created
"a+" yes yes yes end created
add "b" ("rb", "wb") bytes in and out no encoding
add "t" (default) str in and out pass encoding
open() argument Use
encoding="utf-8" always, for text; the default depends on the platform
encoding="utf-8-sig" CSV files from Excel (removes the BOM)
errors="replace" / "backslashreplace" read damaged text without crashing
newline="" always for the csv module, read and write
newline="\n" write Unix line endings on Windows too
buffering=1 line-buffered text output (logs)
File method Does
f.read(), f.read(n) the whole rest / n characters (or bytes)
f.readline() one line with its \n; "" at the end of file
f.readlines() all lines as a list (loads everything)
for line in f: stream lines (best for big files)
f.write(s) write a string; returns the count; adds no \n
f.writelines(lines) write each string; adds no \n
print(..., file=f) write with \n and sep
f.seek(0), f.tell() move to / report the position
f.flush() push the buffer to the OS
from pathlib import Path
out = Path("output")
out.mkdir(exist_ok=True)
log = out / "run.txt"
with open(log, "w", encoding="utf-8") as f: # truncate, then write
f.write("first line\n")
print("second", "line", file=f)
with open(log, "a", encoding="utf-8") as f: # add at the end
f.writelines(["third\n", "fourth\n"])
with open(log, encoding="utf-8") as f:
print(f.readline().rstrip(), "|", [line.rstrip() for line in f])
words = Path("data/readings.txt").read_text(encoding="utf-8").split()
temps = [float(w) for w in words if w.replace(".", "", 1).isdecimal()] # skip "error"
print(len(words), len(temps), min(temps), max(temps))
Output
first line | ['second line', 'third', 'fourth']
42 40 19.3 22.9
from pathlib import Path
with open(Path("output/run.txt"), "x", encoding="utf-8") as f: # never overwrites
f.write("new")
Output
FileExistsError: [Errno 17] File exists: 'output/run.txt'
Situation Do
your own files write and read encoding="utf-8"
Excel CSV export read with utf-8-sig
old Windows or European files try cp1252, then latin-1; check known values
unknown encoding read bytes, try candidates; charset-normalizer guesses
bad bytes in a log errors="replace" (lossy) or "backslashreplace"
Windows line endings \r\n text mode converts them to \n on read
byte-exact processing binary mode "rb"
make UTF-8 the default everywhere PYTHONUTF8=1 or python -X utf8 (default from Python 3.15)
from pathlib import Path
legacy = Path("data/legacy_latin1.csv")
print(legacy.read_text(encoding="latin-1").splitlines()[1])
print(legacy.read_text(encoding="utf-8", errors="replace").splitlines()[1])
Path("output/bom.csv").write_text("id,city\n1,Köln\n", encoding="utf-8-sig")
print(repr(Path("output/bom.csv").read_text(encoding="utf-8")[:4])) # BOM kept
print(repr(Path("output/bom.csv").read_text(encoding="utf-8-sig")[:4])) # BOM removed
Output
SUP01,Café Müller GmbH,Köln,Germany,2015
SUP01,Caf� M�ller GmbH,K�ln,Germany,2015
'\ufeffid,'
'id,c'
Tool Does
csv.reader(f) rows as lists of strings
csv.DictReader(f) rows as dicts; the header gives the keys
csv.writer(f) writerow(list), writerows(rows)
csv.DictWriter(f, fieldnames=[...]) writeheader(), writerow(dict); extrasaction="ignore" drops extra keys
delimiter=";", quotechar='"' other dialects
quoting=csv.QUOTE_NONNUMERIC quote all text; read unquoted fields as float
csv.Sniffer().sniff(sample) guess the delimiter
newline="" required on open() for both reading and writing
import csv
from collections import defaultdict
revenue = defaultdict(float)
with open("data/sales.csv", newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
print(reader.fieldnames[:5])
for row in reader: # every value is a str
revenue[row["region"]] += float(row["revenue"])
with open("output/revenue_by_region.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["region", "revenue"])
writer.writeheader()
for region, total in sorted(revenue.items()):
writer.writerow({"region": region, "revenue": f"{total:.2f}"})
with open("output/revenue_by_region.csv", newline="", encoding="utf-8") as f:
for row in csv.reader(f):
print(row)
Output
['order_id', 'order_date', 'customer_id', 'store_id', 'region']
['region', 'revenue']
['East', '993683.72']
['North', '888229.47']
['South', '891766.07']
['West', '822844.57']
import csv
import io
text = 'id;name;note\n1;"Smith; J.";"said ""hi"""\n'
print(csv.Sniffer().sniff(text).delimiter)
print(list(csv.reader(io.StringIO(text), delimiter=";")))
buffer = io.StringIO()
csv.writer(buffer).writerow(["a,b", 'quote "x"', 3])
print(buffer.getvalue(), end="")
Output
;
[['id', 'name', 'note'], ['1', 'Smith; J.', 'said "hi"']]
"a,b","quote ""x""",3
Python JSON Note
dict object keys become strings: {1: "a"} → {"1": "a"}
list, tuple array a tuple comes back as a list
str string
int, float number nan and inf are written but are not valid JSON
True, False true, false
None null
datetime, Decimal, set, Path TypeError default=str, or convert first
Function Does
json.load(f) / json.loads(s) parse a file / a string
json.dump(obj, f) / json.dumps(obj) write to a file / a string
indent=2 pretty-print
sort_keys=True stable key order
ensure_ascii=False keep é instead of \u00e9
default=str call str on unknown types
separators=(",", ":") the most compact form
json.JSONDecodeError invalid input (a ValueError); has .lineno, .colno
import json
from datetime import date
from pathlib import Path
with open("data/config.json", encoding="utf-8") as f:
config = json.load(f)
print(config["project"], config["thresholds"]["max_discount"], config["model"]["type"])
report = {"city": "Köln", "day": date(2024, 5, 1), "ids": (1, 2), 3: None}
text = json.dumps(report, default=str, ensure_ascii=False)
print(text)
print(json.loads(text)) # the tuple came back as a list, the key 3 as "3"
pretty = json.dumps(report, indent=2, default=str, ensure_ascii=False)
Path("output/report.json").write_text(pretty, encoding="utf-8")
print(Path("output/report.json").read_text(encoding="utf-8").splitlines()[:3])
Output
sales-pipeline 0.2 logistic_regression
{"city": "Köln", "day": "2024-05-01", "ids": [1, 2], "3": null}
{'city': 'Köln', 'day': '2024-05-01', 'ids': [1, 2], '3': None}
['{', ' "city": "Köln",', ' "day": "2024-05-01",']
import json
events = [{"id": 1, "level": "INFO"}, {"id": 2, "level": "ERROR"}]
with open("output/events.jsonl", "w", encoding="utf-8") as f:
for event in events:
f.write(json.dumps(event) + "\n") # JSON Lines: one object per line
with open("output/events.jsonl", encoding="utf-8") as f:
errors = [e for line in f if (e := json.loads(line))["level"] == "ERROR"]
print(errors)
try:
json.loads("{'id': 1}") # single quotes are not JSON
except json.JSONDecodeError as exc:
print(f"line {exc.lineno} col {exc.colno}: {exc.msg}")
Output
[{'id': 2, 'level': 'ERROR'}]
line 1 col 2: Expecting property name enclosed in double quotes
import pickle
from collections import Counter
state = {"counts": Counter("aab"), "seen": {1, 2}, "weights": (0.5, 0.25)}
with open("output/state.pkl", "wb") as f: # binary mode
pickle.dump(state, f)
with open("output/state.pkl", "rb") as f:
restored = pickle.load(f)
print(restored == state, type(restored["counts"]).__name__, restored["seen"])
Output
True Counter {1, 2}
import tomllib
from pathlib import Path
Path("output/settings.toml").write_text(
"""
[project]
name = "sales-pipeline"
version = "1.4.0"
[thresholds]
max_discount = 0.2
regions = ["North", "South"]
start = 2024-01-01
""",
encoding="utf-8",
)
with open("output/settings.toml", "rb") as f: # tomllib needs binary mode
settings = tomllib.load(f)
print(settings["project"], settings["thresholds"]["regions"])
print(settings["thresholds"]["start"], type(settings["thresholds"]["start"]).__name__)
Output
{'name': 'sales-pipeline', 'version': '1.4.0'} ['North', 'South']
2024-01-01 date
Fact Detail
tomllib standard library since 3.11; read only
writing TOML install tomli-w (or tomlkit to keep comments)
types strings, ints, floats, bools, dates and datetimes, arrays, tables
tomllib.loads(text) parse a string
pyproject.toml the standard project config (tooling)
Call Does
shutil.copy(src, dst) copy contents and permissions; dst can be a folder
shutil.copy2(src, dst) also copy timestamps
shutil.copytree(src, dst, dirs_exist_ok=True) copy a folder tree
shutil.move(src, dst) move a file or folder (across drives too)
shutil.rmtree(path) delete a folder tree; no undo
shutil.make_archive(base, "zip", root) create base.zip; also "gztar"
shutil.unpack_archive(file, dest) extract an archive
shutil.disk_usage(path) total, used, free bytes
shutil.which("git") full path of a program, or None
tempfile.TemporaryDirectory() a folder deleted after with
tempfile.NamedTemporaryFile(delete_on_close=False) a file you can reopen by name (3.12+)
tempfile.mkstemp(), mkdtemp() create and keep; you delete it
os.walk(top) (dirpath, dirnames, filenames) for each folder
Path(top).walk() the same with Path objects (3.12+)
os.scandir(path) fast listing with cached stat info
import shutil
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tmp:
root = Path(tmp)
shutil.copytree("data/reports", root / "reports")
shutil.copy2("data/stores.csv", root / "reports")
(root / "reports" / "archive").mkdir()
shutil.move(root / "reports" / "2024-01.csv", root / "reports" / "archive")
for folder, dirs, files in (root / "reports").walk():
dirs.sort() # walk subfolders in a stable order
print(folder.relative_to(root), len(files), sorted(files)[:2])
archive = shutil.make_archive(str(root / "backup"), "zip", root / "reports")
shutil.unpack_archive(archive, root / "restored")
restored = sorted(p.name for p in (root / "restored").iterdir())
print(Path(archive).name, len(restored), restored[-2:])
print("deleted:", not root.exists())
Output
reports 6 ['2024-02.csv', '2024-03.csv']
reports/archive 1 ['2024-01.csv']
backup.zip 7 ['archive', 'stores.csv']
deleted: True
import gzip
import zipfile
from pathlib import Path
with gzip.open("output/readings.txt.gz", "wt", encoding="utf-8") as f:
f.write(Path("data/readings.txt").read_text(encoding="utf-8"))
with gzip.open("output/readings.txt.gz", "rt", encoding="utf-8") as f:
print(f.readline().strip(), Path("output/readings.txt.gz").suffixes)
with zipfile.ZipFile("output/reports.zip", "w", zipfile.ZIP_DEFLATED) as zf:
for path in sorted(Path("data/reports").glob("*.csv"))[:2]:
zf.write(path, arcname=path.name)
with zipfile.ZipFile("output/reports.zip") as zf:
print(zf.namelist(), zf.read("2024-01.csv").decode("utf-8").splitlines()[0])
Output
21.0 ['.txt', '.gz']
['2024-01.csv', '2024-02.csv'] order_id,order_date,store_id,product,category,quantity,revenue
Format Good for Watch out
CSV tables for people and spreadsheets no types: every value is text; delimiters and encodings vary
JSON nested data, APIs, configs no dates, no comments; one big object must fit in memory
JSON Lines logs, streams, append-only records one object per line; no trailing commas
TOML human-edited config (pyproject.toml) read-only in the standard library
YAML config in DevOps tools needs PyYAML; use yaml.safe_load only
Parquet large typed tables (pandas, Polars, DuckDB) binary; needs pyarrow
SQLite many tables, queries, updates sqlite3 in the standard library
pickle Python-only caches you made yourself unsafe to load from others; version-fragile
Excel .xlsx business users needs openpyxl; slow for big data
Trap Symptom Fix
relative paths FileNotFoundError when you run from another folder run from the project root, or build from Path(__file__).parent
open(p, "w") silently erases the file "a" to append, "x" to protect
no encoding= works on macOS, UnicodeDecodeError on Windows encoding="utf-8" every time
CSV without newline="" blank lines between rows on Windows; broken quoted newlines open(p, "w", newline="", encoding="utf-8")
CSV values "42" is a str; "" for missing convert each column; handle ""
Excel CSV first header is '\ufeffid' encoding="utf-8-sig"
f.write(line) lines run together add "\n", or print(..., file=f)
reading after the end f.read() returns "" the second time f.seek(0) or reopen
json.dump of a datetime, set, Decimal TypeError: Object of type date is not JSON serializable default=str, or convert first
JSON keys int keys come back as str convert keys after loading
single quotes in JSON JSONDecodeError: Expecting property name enclosed in double quotes it is not JSON; fix the producer (or ast.literal_eval for Python literals)
tomllib.load(open(p)) TypeError: File must be opened in binary mode open(p, "rb")
pickle.load of a downloaded file arbitrary code runs never unpickle untrusted data
glob / iterdir order differs by OS and run sorted(...)
p.rename(target) on Windows FileExistsError if target exists p.replace(target)
shutil.rmtree on the wrong path data loss print the path and check it first; never build it from user input
TemporaryDirectory path used after with the folder is gone use it inside the block
writing into data/ raw data overwritten write to output/
string paths with \ "C:\new" contains a newline Path, raw strings or /
Path.cwd() vs script folder different when run from elsewhere Path(__file__).resolve().parent for files next to the script