Python — files, CSV and JSON
Read and write files, CSV and JSON, and handle errors during loading.
Prerequisites
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
Sign in to do the exercises and build your mastery up.
Sources
Leads to
Part of the goals (17)
- 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
- Foundations of computer science
- Classical machine learning in practice
- Systems knowledge for AI engineers
- Classical ML for real
- AI in production
- Build an AI service that survives production
- Build an NLP system end to end
- Fine-tune and run your own models
- An AI service in operation
- AI safety in practice
- Build a RAG system you can trust
- Training neural networks for real