Files, Paths, CSV, JSON Lines and Dates
After this lesson, you will be able to:
- Build file paths with pathlib and read or write text with an explicit utf-8 encoding
- Read and write CSV files with csv.DictReader and csv.DictWriter, and explain why split(',') breaks
- Store and stream a dataset as JSON Lines, reading it lazily one line at a time
- Parse and compare timestamps with datetime, keeping them timezone-aware
- Handle missing, malformed and unreadable files with specific exceptions and clear messages
Before you start
#Paths with pathlib
data/train.csv. You could build one by gluing strings together, and the first slip is silent until you open the file:folder = "data"
name = "train.csv"
try:
open(folder + name) # forgot the slash: this looks for "datatrain.csv"
except FileNotFoundError as err:
print(type(err).__name__, err.filename)
from pathlib import Path
data_dir = Path("data")
data_dir.mkdir(exist_ok=True)
train_path = data_dir / "train.csv" # "/" joins path pieces for you
train_path.write_text("text,label\nI loved it,pos\n", encoding="utf-8")
print(train_path) # data/train.csv
print(train_path.name) # train.csv
print(train_path.stem) # train
print(train_path.suffix) # .csv
print(train_path.parent) # data
print(train_path.exists()) # True
print(train_path.with_suffix(".jsonl")) # data/train.jsonl
for p in sorted(data_dir.glob("*.csv")): # every .csv in the folder
print("found", p.name)
print(train_path.read_text(encoding="utf-8"))
print(Path("data/missing.csv").exists())
# Output:
# FileNotFoundError datatrain.csv
# data/train.csv
# train.csv
# train
# .csv
# data
# True
# data/train.jsonl
# found train.csv
# text,label
# I loved it,pos
#
# Falsepathlib.Path is an object that knows it is a path. The / operator joins pieces with the right separator for the operating system (on Windows print shows backslashes), and the properties name, stem, suffix and parent replace string slicing. Prefer Path over the older os.path functions in new code.data/train.csv is resolved against the current working directory, the folder the program was started from, and Path.cwd() shows it. A script that works from one folder and fails from another usually has a relative path. In the browser your files live in the page's own temporary filesystem and disappear when you reload, which is why every cell here writes its sample files first.#Reading and Writing Text Files
open(path, mode, encoding=...) returns a file object: a cursor moving through the file. Because you already know with, you know the rest of the shape: the block closes the file for you, even if an exception fires inside it. Always open files with with.| Mode | Meaning | Creates the file? | Erases existing content? |
|---|---|---|---|
"r" | read text (the default) | No | No |
"w" | write text | Yes | Yes |
"a" | append to the end | Yes | No |
"x" | create, fail if it exists | Yes | No |
b ("rb", "wb") for raw bytes, which you need for pickle and images but not for text. The example uses a training log, because logs are appended to and read back line by line:from pathlib import Path
log_path = Path("train.log")
with open(log_path, "w", encoding="utf-8") as f:
f.write("epoch 1 loss 0.92\n") # write() adds no newline: you type \n
f.write("epoch 2 loss 0.61\n")
with open(log_path, "a", encoding="utf-8") as f: # "a" adds to the end
f.write("epoch 3 loss 0.48\n")
losses = []
with open(log_path, encoding="utf-8") as f:
for line in f: # one line at a time, constant memory
print(line.rstrip()) # rstrip() removes the trailing newline
losses.append(float(line.split()[-1]))
print(losses)
with open(log_path, "w", encoding="utf-8") as f: # "w" erases the file first
f.write("epoch 1 loss 0.90\n")
print(log_path.read_text(encoding="utf-8").strip())
try:
with open(log_path, "x", encoding="utf-8") as f:
f.write("never written")
except FileExistsError:
print("x refused to overwrite")
# Output:
# epoch 1 loss 0.92
# epoch 2 loss 0.61
# epoch 3 loss 0.48
# [0.92, 0.61, 0.48]
# epoch 1 loss 0.90
# x refused to overwritefor line in f) reads one line at a time, so a 10 GB log costs the memory of one line. f.read() and f.readlines() load everything, which is fine for a small config file and a problem for a large dataset. For a small file, Path.read_text() and Path.write_text() do the open, read and close in one call.A file contains the two lines hello and world. What does this print? with open("data.txt") as f: for line in f: print(line)
What happens if you open an existing file with mode 'w' and write one line?
#Encodings: Always Say utf-8
encoding out, Python picks one from the operating system's settings, and that choice is not the same on every machine (Windows has commonly used a legacy code page). A program that works on your laptop can then fail, or worse, silently garble text, on a colleague's machine.from pathlib import Path
Path("reviews.txt").write_text("café, naïve\n", encoding="utf-8")
print(Path("reviews.txt").read_bytes())
with open("reviews.txt", encoding="latin-1") as f: # the wrong encoding, no error
print(f.read().strip())
try:
with open("reviews.txt", encoding="ascii") as f: # a stricter wrong encoding
f.read()
except UnicodeDecodeError as err:
print(err)
with open("reviews.txt", encoding="utf-8") as f: # the right one
print(f.read().strip())
# Output:
# b'caf\xc3\xa9, na\xc3\xafve\n'
# café, naïve
# 'ascii' codec can't decode byte 0xc3 in position 3: ordinal not in range(128)
# café, naïveUnicodeDecodeError or, worse, reads garbage without complaint (the garbled café is called mojibake). The habit is simple: write encoding="utf-8" on every text open(), read_text() and write_text().#CSV: Do Not Split on Commas
line.split(","), until a cell contains a comma. CSV handles that by wrapping the cell in double quotes, and split knows nothing about quotes:import csv
from pathlib import Path
raw = 'text,label\n"Great, but slow",pos\nTerrible,neg\n'
for line in raw.splitlines()[1:]:
print(line.split(",")) # the first row comes out as THREE pieces
Path("reviews.csv").write_text(raw, encoding="utf-8")
with open("reviews.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f): # each row becomes a dict keyed by the header
print(row)
# Output:
# ['"Great', ' but slow"', 'pos']
# ['Terrible', 'neg']
# {'text': 'Great, but slow', 'label': 'pos'}
# {'text': 'Terrible', 'label': 'neg'}csv.DictReader reads the header row for the keys and handles quotes, embedded commas, doubled quotes and even newlines inside a cell. Writing is the mirror image: csv.DictWriter adds the quotes when a cell needs them.import csv
from pathlib import Path
rows = [
{"text": "Great, but slow", "label": "pos", "score": 0.81},
{"text": 'He said "no"', "label": "neg", "score": 0.12},
{"text": "two\nlines", "label": "neg", "score": 0.30},
]
with open("scored.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["text", "label", "score"])
writer.writeheader()
writer.writerows(rows)
print(Path("scored.csv").read_text(encoding="utf-8"))
with open("scored.csv", newline="", encoding="utf-8") as f:
back = list(csv.DictReader(f))
print(back[2])
print(back[0]["score"] + back[1]["score"]) # strings join
print(float(back[0]["score"]) + float(back[1]["score"])) # numbers add
# Output:
# text,label,score
# "Great, but slow",pos,0.81
# "He said ""no""",neg,0.12
# "two
# lines",neg,0.3
#
# {'text': 'two\nlines', 'label': 'neg', 'score': '0.3'}
# 0.810.12
# 0.93newline="" when you open a file for the csv module, so it can handle line breaks inside quoted cells itself. Second, CSV has no types: every value comes back as a string, so "0.81" + "0.12" is "0.810.12". Convert with float() or int() yourself. If the result looks wrong, print one row before you debug anything else.#JSON and JSON Lines
null. json.dumps(obj) makes a string, json.loads(text) reads one, and json.dump(obj, f) and json.load(f) do the same with an open file. Pass ensure_ascii=False to keep characters such as é readable instead of escaped as \u00e9..jsonl) fixes this with one rule: each line is one complete JSON object. Datasets of labelled examples and experiment logs are commonly stored this way, because you can append a record, stream the file one line at a time, and lose at most the last line to a crash.import json
from pathlib import Path
examples = [
{"text": "great, fast delivery", "label": "pos"},
{"text": "café was cold", "label": "neg"},
{"text": "okay I guess", "label": "neu"},
]
path = Path("examples.jsonl")
with open(path, "w", encoding="utf-8") as f:
for ex in examples:
f.write(json.dumps(ex, ensure_ascii=False) + "\n") # one object per line
print(path.read_text(encoding="utf-8").strip())
try:
with open(path, encoding="utf-8") as f:
json.load(f) # the whole file is not ONE json document
except json.JSONDecodeError as err:
print("json.load failed:", err)
with open(path, "a", encoding="utf-8") as f: # appending is one write
f.write(json.dumps({"text": "late addition", "label": "pos"}) + "\n")
f.write("{not json}\n") # a corrupt line
def read_jsonl(path):
"""Yield one dict per line, skipping blank and corrupt lines."""
with open(path, encoding="utf-8") as f:
for line_no, line in enumerate(f, start=1):
line = line.strip()
if not line:
continue
try:
yield json.loads(line)
except json.JSONDecodeError as err:
print(f"line {line_no}: skipped ({err.msg})")
counts = {}
for ex in read_jsonl(path):
counts[ex["label"]] = counts.get(ex["label"], 0) + 1
print(counts)
print(next(read_jsonl(path))) # a generator reads only as far as you ask
# Output:
# {"text": "great, fast delivery", "label": "pos"}
# {"text": "café was cold", "label": "neg"}
# {"text": "okay I guess", "label": "neu"}
# json.load failed: Extra data: line 2 column 1 (char 49)
# line 5: skipped (Expecting property name enclosed in double quotes)
# {'pos': 2, 'neg': 1, 'neu': 1}
# {'text': 'great, fast delivery', 'label': 'pos'}read_jsonl is a generator, so it holds one line at a time however large the file is, and next(...) read only the first line. The try sits around json.loads alone, so a bad line is reported with its number and the loop carries on.#Dates and Times
datetime module gives you three tools. A datetime is a point in time. A timedelta is a length of time, and subtracting two datetimes gives one. And fromisoformat / isoformat convert to and from ISO 8601 strings such as 2025-03-09T14:05:00+00:00, the unambiguous format to store in files.from datetime import datetime, timedelta, timezone
started = datetime.fromisoformat("2025-03-09T14:05:00+00:00")
finished = datetime.fromisoformat("2025-03-09T16:47:30+00:00")
run_time = finished - started # a timedelta
print(run_time, run_time.total_seconds())
print(started + timedelta(hours=6))
print(started.strftime("%Y-%m-%d %H:%M")) # format to a string you choose
print(datetime.strptime("09/03/2025 14:05", "%d/%m/%Y %H:%M")) # parse a custom format
print(started.isoformat())
# Output:
# 2:42:30 9750.0
# 2025-03-09 20:05:00+00:00
# 2025-03-09 14:05
# 2025-03-09 14:05:00
# 2025-03-09T14:05:00+00:00+00:00). A naive one is only a clock reading such as 14:05, with no way to know in which city. Python refuses to mix them in arithmetic, which is a kindness, because the "fix" people reach for is worse than the error:from datetime import datetime, timedelta, timezone
server = datetime.fromisoformat("2025-03-09T14:05:00+00:00") # aware, UTC
laptop = datetime.fromisoformat("2025-03-09T19:35:00") # naive: the laptop's local clock
print(laptop.tzinfo)
try:
print(server - laptop)
except TypeError as err:
print("TypeError:", err)
guess = laptop.replace(tzinfo=timezone.utc) # "make it aware" by guessing UTC
print((server - guess).total_seconds() / 3600, "hours apart")
ist = timezone(timedelta(hours=5, minutes=30))
truth = laptop.replace(tzinfo=ist) # the laptop was on UTC+05:30
print((server - truth).total_seconds() / 3600, "hours apart")
print(truth.astimezone(timezone.utc))
print(datetime.now(timezone.utc).tzinfo) # how to take "now" as an aware UTC time
# Output:
# None
# TypeError: can't subtract offset-naive and offset-aware datetimes
# -5.5 hours apart
# 0.0 hours apart
# 2025-03-09 14:05:00+00:00
# UTCdatetime.now(timezone.utc)), store them as ISO strings, and convert to a local zone only to display them. timezone(timedelta(...)) is a fixed offset and does not know about daylight saving; the zoneinfo module does, and in the browser it needs a timezone database that is not loaded by default, so it is not used here.a = datetime.fromisoformat("2025-03-09T10:00:00+00:00") b = datetime.fromisoformat("2025-03-09T10:30:00") What does print(a - b) do?
#Handling File Errors
try, except, else and finally in full. Here is how they apply to files. Each failure has its own exception, and you catch the one you can do something about:| Exception | When it happens |
|---|---|
FileNotFoundError | the path does not exist |
PermissionError | you may not read or write it |
IsADirectoryError | you opened a folder as a file |
UnicodeDecodeError | the bytes do not match the encoding |
json.JSONDecodeError | the text is not valid JSON (it is a ValueError) |
try around the smallest piece of code that can fail, so you do not hide unrelated bugs. And decide per problem whether to stop or to skip: a missing file means you cannot continue, while one bad row in a large dataset is better reported and skipped. Raise your own ValueError with the row number and the offending value when a row breaks your rules.import json
from pathlib import Path
LABELS = {"pos", "neg", "neu"}
def check_example(row_no, ex):
"""Raise ValueError with a clear message if the row breaks the rules."""
if "text" not in ex or "label" not in ex:
raise ValueError(f"row {row_no}: needs text and label, got keys {sorted(ex)}")
if ex["label"] not in LABELS:
raise ValueError(f"row {row_no}: unknown label {ex['label']!r}")
def load_examples(path):
"""Return (good_rows, problems). A missing file is an error; a bad row is a note."""
good, problems = [], []
try:
f = open(path, encoding="utf-8")
except FileNotFoundError:
raise FileNotFoundError(f"dataset not found: {path}") from None
with f:
for row_no, line in enumerate(f, start=1):
try:
ex = json.loads(line)
check_example(row_no, ex)
good.append(ex)
except json.JSONDecodeError as err: # a ValueError subclass: catch it first
problems.append(f"row {row_no}: not valid JSON ({err.msg})")
except ValueError as err: # the rule violations raised above
problems.append(str(err))
return good, problems
Path("mixed.jsonl").write_text(
'{"text": "ok", "label": "pos"}\n'
'{"text": "no label"}\n'
'{"text": "meh", "label": "maybe"}\n'
'{broken\n',
encoding="utf-8",
)
good, problems = load_examples("mixed.jsonl")
print(len(good), "good,", len(problems), "problems")
for p in problems:
print(" ", p)
try:
load_examples("nope.jsonl")
except FileNotFoundError as err:
print(err)
# Output:
# 1 good, 3 problems
# row 2: needs text and label, got keys ['text']
# row 3: unknown label 'maybe'
# row 4: not valid JSON (Expecting property name enclosed in double quotes)
# dataset not found: nope.jsonl#Saving Python Objects
null. Pickle (pickle) stores almost any Python object, but only Python can read it, and it is binary, so the file is opened with "wb" and "rb":import json
import pickle
state = {"player": "Asha", "position": (14, 22), "inventory": ["torch"]}
with open("save.json", "w", encoding="utf-8") as f:
json.dump(state, f)
with open("save.pkl", "wb") as f:
pickle.dump(state, f)
with open("save.json", encoding="utf-8") as f:
print(json.load(f)["position"]) # the tuple came back as a list
with open("save.pkl", "rb") as f:
print(pickle.load(f)["position"]) # still a tuple
try:
json.dumps({"tags": {"a", "b"}})
except TypeError as err:
print(err)
# Output:
# [14, 22]
# (14, 22)
# Object of type set is not JSON serializable#Try It: A JSONL Cleaner
clean_jsonl(src, dst), which reads a JSON Lines file lazily, keeps only the valid examples, writes them to a new file and returns how many it kept along with a note for every rejected line. Use with for both files, an explicit encoding, and one try around json.loads.Tests: Expect: kept 3, then three notes (lines 3, 4 and 5), then the three clean examples.
This program writes a note to a file and then reads it back. The read returns an empty string because the writer was never closed. Fix it with a context manager.
Got: hello from python
#Key Takeaways
- Build paths with
pathlib.Pathand the/operator, and writeencoding="utf-8"on every text open,read_textandwrite_text. - Open files with
with. Know your modes:"r"reads,"w"erases and writes,"a"appends,"x"refuses to overwrite. - Do not split CSV by hand. Use
csv.DictReaderandcsv.DictWriterwithnewline="", and convert the string values to numbers yourself. - Use JSON Lines for datasets and logs. One JSON object per line lets you append, stream lazily with a generator, and skip a corrupt line.
- Keep timestamps timezone-aware. Take them with
datetime.now(timezone.utc), store them as ISO strings and subtract to get atimedelta. - Catch specific exceptions around the smallest risky code, report bad rows with their line number, and never unpickle a file you did not write.
A CSV file has the row `"Great, but slow",pos`. What does `line.split(",")` return for that line?