Lesson 04
Files, errors, and testing
Work with files safely, handle failure gracefully, and get fast feedback with tests.
File I/O
# Read a whole file
from pathlib import Path
p = Path("data.txt")
text = p.read_text(encoding="utf-8")
print(len(text))
# Write safely with context manager
with open("out.txt", "w", encoding="utf-8") as f:
f.write("hello\n")
# CSV and JSON
import csv, json
rows = [("SIG", 12.34), ("EURUSD", 1.074)]
with open("prices.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["symbol","price"])
writer.writerows(rows)
print(json.dumps({"ok": True, "count": len(rows)}))
Errors and exceptions
def parse_price(s: str) -> float:
try:
return float(s)
except ValueError as e:
raise ValueError(f"invalid price: {s}") from e
finally:
pass # close resources if you opened anything
# Using try/except/else
value = "12.5"
try:
price = parse_price(value)
except ValueError as e:
print(e)
else:
print("parsed:", price)
Testing with pytest
# test_app.py
from app import parse_price
def test_parse_price_ok():
assert parse_price("12.5") == 12.5
def test_parse_price_bad():
import pytest
with pytest.raises(ValueError):
parse_price("N/A")
Run tests with pytest -q. Keep tests small and focused.
Accelerate with SigLabs Financial Software
Forecasting, market screening, risk insights, and reporting—built for speed and clarity.
Next steps
Next up: OOP, async, and HTTP in Lesson 05.