Python — files, CSV and JSON
Read and write files, CSV and JSON, and handle errors during loading.
Intuition
Data is stored in files. Three formats you will encounter frequently in professional work:
- Text file (.txt): simple lines.
- CSV: tabular format, one row per record, columns separated by commas or semicolons.
- JSON: nested structures (lists and dictionaries) that correspond to Python's
listanddict.
Always open files with with open(...) as f: so that the file is closed automatically, even if an error occurs. Specify encoding="utf-8" to avoid issues with special characters such as å, ä and ö.
Code
import csv, json
with open("anstallda.csv", encoding="utf-8") as f:
rader = list(csv.DictReader(f, delimiter=";"))
print(rader[0]) # {'namn': 'Anna', 'timmar': '14'}
total = sum(int(r["timmar"]) for r in rader)
data = {"avdelning": "IT", "anstallda": rader}
with open("avdelning.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
try:
with open("saknas.csv") as f:
...
except FileNotFoundError:
print("Filen hittades inte — kontrollera sökvägen")
The CSV reader always returns strings — you must convert them to numbers yourself. JSON preserves data types (numbers, lists, boolean values).
Mastery means
- Read and write text files using with
- Read CSV and JSON into Python structures
- Handle errors during loading
Prerequisites
Sign in to do the exercises and build your mastery up.
Sources
Leads to
Part of the goals (16)
- Language models in practice
- The developer's toolbox
- Build a memory system for an agent
- Build an agent you can trust
- Data: collect, clean, document
- Classical machine learning in practice
- Classical ML for real
- Systems knowledge for AI engineers
- Foundations of computer science
- Fine-tune and run your own models
- AI in production
- Build an NLP system end to end
- Build an AI service that survives production
- Training neural networks for real
- AI safety in practice
- An AI service in operation