Working with JSON and CSV

Turn data into text and back with the `json` module, keep Azerbaijani letters readable with `ensure_ascii=False`, read and write tables correctly with the `csv` module, and handle files with `pathlib`.

  • Advanced
  • 20 min
  • 10 questions
  • Lesson 36 of 66

In this lesson you will learn

  • Convert Python objects to JSON and back with json.dumps, json.loads, json.dump and json.load
  • Read CSV with csv.reader and csv.DictReader and write it with csv.writer and DictWriter
  • Build paths and read and write files with pathlib.Path

The lesson you are reading right now is itself a JSON file: the website and the mobile apps take it from the same file. Programs mostly exchange data in two text formats: JSON — the language of web services, settings files and APIs — and CSV — tables coming from Excel, bank statements and reports. Python's standard library has ready-made modules for both.

JSON: data as text

JSON (JavaScript Object Notation) looks a lot like Python dictionaries and lists, with a few differences: strings use only double quotes, true replaces True, null replaces None, and object keys are always strings. json.dumps turns a Python object into a JSON string (serialization), and json.loads does the reverse.

PythonJSON
dictobject {...}
list, tuplearray [...]
strstring (in double quotes)
int, floatnumber
True, False, Nonetrue, false, null
Python
import json

student = {'name': 'Aysel', 'city': 'Bakı', 'age': 19,
           'grades': [5, 4, 5], 'active': True, 'mentor': None}
text = json.dumps(student)
print(text)
print(json.dumps(student, ensure_ascii=False))
back = json.loads(text)
print(back == student, type(back['grades']).__name__)
print(json.dumps({'city': 'Gəncə', 'grades': [5, 4]}, ensure_ascii=False, indent=2))
Expected output
{"name": "Aysel", "city": "Bak\u0131", "age": 19, "grades": [5, 4, 5], "active": true, "mentor": null}
{"name": "Aysel", "city": "Bakı", "age": 19, "grades": [5, 4, 5], "active": true, "mentor": null}
True list
{
  "city": "Gəncə",
  "grades": [
    5,
    4
  ]
}
Python
import json
from datetime import date

data = {1: 'one', 'point': (3, 4)}
text = json.dumps(data)
print(text)
print(json.loads(text))
try:
    json.dumps({'when': date(2026, 9, 1)})
except TypeError as e:
    print('TypeError:', e)
print(json.dumps({'when': date(2026, 9, 1)}, default=str))
Expected output
{"1": "one", "point": [3, 4]}
{'1': 'one', 'point': [3, 4]}
TypeError: Object of type date is not JSON serializable
{"when": "2026-09-01"}

Sign up free to keep reading

The rest of the lesson, the quiz and your notes open with an Educora account. Signing up takes a minute, and your progress is saved on all your devices.

pathlib and JSON files

pathlib.Path represents a file path as an object: paths are joined with / (Path('data') / 'report.json'), read_text and write_text read and write a file in one line, name, stem and suffix return parts of the name, and exists() tells whether the file is there. The code works the same on Windows, macOS and Linux. For open file objects there are json.dump and json.load.

Python
import json
from pathlib import Path

settings = {'language': 'az', 'theme': 'dark', 'subjects': ['python', 'math']}
path = Path('settings.json')
path.write_text(json.dumps(settings, indent=2), encoding='utf-8')
loaded = json.loads(path.read_text(encoding='utf-8'))
print(loaded['subjects'])

with open(path, 'w', encoding='utf-8') as f:
    json.dump(settings, f, ensure_ascii=False)
with open(path, encoding='utf-8') as f:
    print(json.load(f) == settings)
print(path.name, path.stem, path.suffix, path.exists())
Expected output
['python', 'math']
True
settings.json settings .json True
Remember: dumps / loads work with strings, while dump / load work with files (the “s” stands for string).

CSV: tables with the csv module

CSV looks simple, but a quoted field can contain a comma, a line break or even a quote character. The csv module knows these rules. csv.reader returns each row as a list, and csv.DictReader as a dictionary keyed by the header names. All values are strings — convert numbers yourself.

Python
import csv
import io

text = '''name,city,score
Aysel,Bakı,91
Murad,"Gəncə, Azerbaijan",76
Leyla,Sumqayıt,85'''
for row in csv.reader(io.StringIO(text)):
    print(row)
rows = list(csv.DictReader(io.StringIO(text)))
print(rows[1]['city'], '|', type(rows[1]['score']).__name__)
avg = sum(int(r['score']) for r in rows) / len(rows)
print(f'average: {avg:.1f}')
print('Murad,"Gəncə, Azerbaijan",76'.split(','))
Expected output
['name', 'city', 'score']
['Aysel', 'Bakı', '91']
['Murad', 'Gəncə, Azerbaijan', '76']
['Leyla', 'Sumqayıt', '85']
Gəncə, Azerbaijan | str
average: 84.0
['Murad', '"Gəncə', ' Azerbaijan"', '76']

For writing, use csv.writer (lists) or csv.DictWriter (dictionaries). The module adds quotes where they are needed by itself. By the standard, rows end with \r\n; here we pass lineterminator='\n' to print the result on screen.

Python
import csv
import io

rows = [{'product': 'Tea', 'price': 4.5, 'qty': 30},
        {'product': 'Coffee, large', 'price': 6.0, 'qty': 25}]
buf = io.StringIO()
writer = csv.DictWriter(buf, fieldnames=['product', 'price', 'qty'], lineterminator='\n')
writer.writeheader()
writer.writerows(rows)
print(buf.getvalue(), end='')
buf2 = io.StringIO()
csv.writer(buf2, delimiter=';', lineterminator='\n').writerow(['Tea', '4,5', 30])
print(buf2.getvalue(), end='')
Expected output
product,price,qty
Tea,4.5,30
"Coffee, large",6.0,25
Tea;4,5;30

Mini project: from CSV to a JSON report

The grades are in a CSV file, and a mobile app expects a summary by group as JSON. The program creates a data folder, reads the CSV with DictReader, collects the scores by group and writes the report to report.json.

Python
import csv
import json
from pathlib import Path

folder = Path('data')
folder.mkdir(exist_ok=True)
(folder / 'grades.csv').write_text(
    'name,group,score\nAysel,A,91\nMurad,B,76\nLeyla,A,85\nElvin,B,64\n', encoding='utf-8')

with open(folder / 'grades.csv', newline='', encoding='utf-8') as f:
    rows = list(csv.DictReader(f))

groups = {}
for r in rows:
    groups.setdefault(r['group'], []).append(int(r['score']))
report = {g: {'count': len(s), 'average': round(sum(s) / len(s), 1)} for g, s in groups.items()}

(folder / 'report.json').write_text(json.dumps(report, indent=2), encoding='utf-8')
print((folder / 'report.json').read_text(encoding='utf-8'))
print(sorted(p.name for p in folder.glob('*')))
Expected output
{
  "A": {
    "count": 2,
    "average": 88.0
  },
  "B": {
    "count": 2,
    "average": 70.0
  }
}
['grades.csv', 'report.json']
mkdir(exist_ok=True) does not fail if the folder already exists, and glob('*') lists the files in the folder. In the browser the files live in a temporary in-memory file system.

Exercise

Read the orders from the JSON string. On the first line print the total of all orders (rounded to 2 decimal places), and on the second line print the totals by city as JSON: Azerbaijani letters must not be escaped and the keys must be sorted.

Exercise · Python
import json

text = '[{"customer": "Aysel", "city": "Bakı", "total": 45.5}, {"customer": "Murad", "city": "Gəncə", "total": 30.0}, {"customer": "Leyla", "city": "Bakı", "total": 12.5}]'
# 1) total of all orders
# 2) totals by city as JSON (ensure_ascii=False, sort_keys=True)
Expected output
88.0
{"Bakı": 58.0, "Gəncə": 30.0}

Exercise

Read the CSV with csv.DictReader. On the first line print, as a dictionary, how many students come from each city; on the second line print the city with the highest average score and that average (separated by a space).

Exercise · Python
import csv
import io

text = '''name,city,score
Aysel,Bakı,91
Murad,Gəncə,76
Leyla,Bakı,85
Elvin,Gəncə,64
Nigar,Sumqayıt,88'''
# count students per city, then find the city with the best average
Expected output
{'Bakı': 2, 'Gəncə': 2, 'Sumqayıt': 1}
Bakı 88.0

Remember

  • dumps / loads work with strings and dump / load with files; JSON has true, false, null and only string keys.
  • For Azerbaijani text use ensure_ascii=False and encoding='utf-8'; use indent=2 for readability.
  • Dates and sets cannot be written to JSON directly: use default=str or ISO strings.
  • Read and write CSV with the csv module, not split(','); open files with newline=''.
  • pathlib.Path: paths with /, read_text, write_text, mkdir(exist_ok=True), glob.
Spotted a mistake or something inaccurate in this lesson?

Check yourself

10 questions. Every correct answer earns XP.

Question 1 / 10

Question 1 / 10. What does json.dumps({'ok': True, 'x': None}) return?