Skip to content
AI-grafen
CBuilderProgramming· about 30 min· fundamentals that rarely change· verified 2026-09-20· EN

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 list and dict.

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

All the sources and licences