Python course · Module 7: Files and errors · Lesson 34 of 63
Quick answer: Python’s json module turns Python data into JSON text and back: json.dumps(data) gives a string, json.loads(text) gives Python data, and json.dump() and json.load() do the same with an open file. The csv module reads and writes tables: csv.reader gives each row as a list of strings, and csv.DictReader gives each row as a dictionary. Open CSV files with newline="" and every file with encoding="utf-8".
In this lesson you will learn:
- how to save and load JSON with
dumps(),loads(),dump()andload() - what
indentandensure_asciido, and how Python types become JSON types - how to read and write CSV files with
reader,writer,DictReaderandDictWriter - why CSV files need
newline="" - how to convert CSV to JSON and back, with real data about Python versions
Before you start: finish Lesson 33, Python pathlib: Work with File Paths the Modern Way. You need open() and with from Lesson 32 and dictionaries from Lesson 17. All examples were run on Linux with Python 3.14.6 and gave the same output on Python 3.15.2, the newest release on python.org, apart from Python’s install folder in the error messages.
Table of Contents
What JSON and CSV files are
JSON (JavaScript Object Notation) is a text format for data with names and nesting, like a dictionary that holds lists. Apps use it for settings and web APIs send it. The json docs call it “a lightweight data interchange format”.
CSV (comma-separated values) is a table in a text file: one line per row, with commas between the columns. Spreadsheet programs can open and save it.
Both modules are in the standard library, so there is nothing to install.
Python json: dumps() turns data into JSON text
Our running JSON example is the settings of a study app:
import json
settings = {
"name": "Sara",
"lesson": 34,
"dark_mode": True,
"font_size": 14.5,
"courses": ["Python", "SQL"],
"teacher": None,
}
text = json.dumps(settings)
print(type(text).__name__)
print(text)
print(json.dumps(settings, indent=2))
str
{"name": "Sara", "lesson": 34, "dark_mode": true, "font_size": 14.5, "courses": ["Python", "SQL"], "teacher": null}
{
"name": "Sara",
"lesson": 34,
"dark_mode": true,
"font_size": 14.5,
"courses": [
"Python",
"SQL"
],
"teacher": null
}
dumps()means “dump to a string”. The result is astr, ready to save or send.- JSON writes
Trueastrue,Noneasnull, and always uses double quotes. indent=2puts each item on its own line with two spaces per level. Without it, everything is on one line.
json.loads(): JSON text back to Python
import json
text = '{"name": "Ali", "lesson": 12, "dark_mode": false, "courses": ["SQL"], "teacher": null}'
data = json.loads(text)
print(type(data).__name__)
print(data)
print(data["courses"][0], data["dark_mode"], data["teacher"])
print(type(data["lesson"]).__name__)
dict
{'name': 'Ali', 'lesson': 12, 'dark_mode': False, 'courses': ['SQL'], 'teacher': None}
SQL False None
int
A JSON object becomes a dict, an array becomes a list, false becomes False and null becomes None. Numbers come back as numbers, so lesson is an int again.
ensure_ascii: keep letters like é readable
import json
dessert = {"food": "Crème brûlée", "price": 450}
print(json.dumps(dessert))
print(json.dumps(dessert, ensure_ascii=False))
{"food": "Cr\u00e8me br\u00fbl\u00e9e", "price": 450}
{"food": "Crème brûlée", "price": 450}
By default ensure_ascii is True. The docs say the output then has “all incoming non-ASCII and non-printable characters escaped”, so è becomes \u00e8. Both lines load back to the same text. Use ensure_ascii=False when people will read the file, and write the file with encoding="utf-8".
json.dump() and json.load(): save and load a file
The versions without the s work with an open file:
import json
from pathlib import Path
settings = {
"name": "Sara",
"lesson": 34,
"dark_mode": True,
"favourite_food": "Crème brûlée",
"courses": ["Python", "SQL"],
}
with open("settings.json", "w", encoding="utf-8") as f:
json.dump(settings, f, indent=2, ensure_ascii=False)
print(Path("settings.json").read_text(encoding="utf-8"))
with open("settings.json", encoding="utf-8") as f:
loaded = json.load(f)
print(loaded["favourite_food"], loaded["courses"])
print(loaded == settings)
{
"name": "Sara",
"lesson": 34,
"dark_mode": true,
"favourite_food": "Crème brûlée",
"courses": [
"Python",
"SQL"
]
}
Crème brûlée ['Python', 'SQL']
True
json.dump(data, f)writes the JSON into the filef;json.load(f)reads the whole file and returns the data.read_text()from Lesson 33 shows the file as it is saved.loaded == settingsisTrue: the round trip gave back the same dictionary.
Python and JSON types
JSON has fewer types than Python. This table comes from the conversion tables in the json docs:
| Python | JSON | Back to Python |
|---|---|---|
| dict | object | dict |
| list, tuple | array | list |
| str | string | str |
| int | number | int |
| float | number | float |
| True, False | true, false | True, False |
| None | null | None |
So some data changes on the way:
import json
original = {"point": (3, 4), 1: "first", "scores": [90, 85.5]}
text = json.dumps(original)
back = json.loads(text)
print(text)
print(back)
print(back == original)
{"point": [3, 4], "1": "first", "scores": [90, 85.5]}
{'point': [3, 4], '1': 'first', 'scores': [90, 85.5]}
False
- The tuple
(3, 4)came back as the list[3, 4]. - The key
1came back as the string"1". The docs say JSON keys “are always of the type str”, soloads(dumps(x)) != xwhenxhas keys that are not strings.
Some types have no JSON form at all, like a set:
import json
student = {"name": "Sara", "skills": {"Python", "SQL"}}
print(json.dumps(student))
The traceback ends with:
TypeError: Object of type set is not JSON serializable
when serializing dict item 'skills'
The second line, which names the bad item, is a note that Python 3.14 added to JSON errors (What’s New in Python 3.14); Python 3.13 printed only the first line in our test. Turn the set into a list first: list(student["skills"]).
JSONDecodeError: when the text is not valid JSON
JSON is stricter than Python. Single quotes are not allowed:
import json
data = json.loads("{'name': 'Sara'}")
The traceback ends with:
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
The message tells you where the problem is: line 1, column 2, which is the ' after {. JSONDecodeError is a kind of ValueError. A comma after the last item fails too: '{"name": "Sara",}' gives Illegal trailing comma before end of object: line 1 column 16 (char 15). In Lesson 35 you will learn to catch these errors so a bad file does not stop your program.
Python CSV: write rows with csv.writer
Our CSV example uses real data: the Python versions in the “Active Python releases” table on python.org/downloads, as listed on 8 November 2026.
import csv
rows = [
["version", "status", "first_released", "end_of_support"],
["3.15", "bugfix", "2026-10-09", "2031-10"],
["3.14", "bugfix", "2025-10-07", "2030-10"],
["3.13", "security", "2024-10-07", "2029-10"],
["3.12", "security", "2023-10-02", "2028-10"],
["3.11", "security", "2022-10-24", "2027-10"],
["3.10", "end-of-life, last release was 3.10.22", "2021-10-04", "2026-10-01"],
]
with open("releases.csv", "w", encoding="utf-8", newline="") as f:
writer = csv.writer(f)
writer.writerows(rows)
with open("releases.csv", encoding="utf-8", newline="") as f:
text = f.read()
print(text, end="")
print(repr(text.splitlines(keepends=True)[-1]))
version,status,first_released,end_of_support
3.15,bugfix,2026-10-09,2031-10
3.14,bugfix,2025-10-07,2030-10
3.13,security,2024-10-07,2029-10
3.12,security,2023-10-02,2028-10
3.11,security,2022-10-24,2027-10
3.10,"end-of-life, last release was 3.10.22",2021-10-04,2026-10-01
'3.10,"end-of-life, last release was 3.10.22",2021-10-04,2026-10-01\r\n'
writerows()writes a list of rows;writerow()writes one row.- The 3.10 status contains a comma, so the writer put it in double quotes. Without the quotes, a reader would see five columns instead of four.
- The
repr()shows that the csv module ends each row with\r\nby itself. This is why the file is opened withnewline="".
Read rows with csv.reader
import csv
with open("releases.csv", encoding="utf-8", newline="") as f:
reader = csv.reader(f)
header = next(reader)
print(header)
for row in reader:
first_year = int(row[2][:4])
end_year = int(row[3][:4])
print(row[0], "is supported for", end_year - first_year, "years")
print(row)
print(type(row[0]).__name__, repr(row[0]))
['version', 'status', 'first_released', 'end_of_support']
3.15 is supported for 5 years
3.14 is supported for 5 years
3.13 is supported for 5 years
3.12 is supported for 5 years
3.11 is supported for 5 years
3.10 is supported for 5 years
['3.10', 'end-of-life, last release was 3.10.22', '2021-10-04', '2026-10-01']
str '3.10'
- Each row is a list.
next(reader)takes the first row, the header, so the loop only sees data rows. - The quoted status came back as one value, with its comma.
- The docs say “No automatic data type conversion is performed”: every value is a string. We cut the year with
[:4]and convert it withint()from Lesson 8. Keep versions as strings:float("3.10")is3.1.
DictReader and DictWriter: rows as dictionaries
Column numbers like row[3] are easy to mix up. DictReader uses the header row as keys:
import csv
with open("releases.csv", encoding="utf-8", newline="") as f:
releases = list(csv.DictReader(f))
print(releases[0])
print(len(releases), "rows")
for release in releases:
if release["status"] == "bugfix":
print(release["version"], "gets bug fixes until", release["end_of_support"])
{'version': '3.15', 'status': 'bugfix', 'first_released': '2026-10-09', 'end_of_support': '2031-10'}
6 rows
3.15 gets bug fixes until 2031-10
3.14 gets bug fixes until 2030-10

DictWriter writes dictionaries. You must give it fieldnames, the columns in order:
import csv
with open("releases.csv", encoding="utf-8", newline="") as f:
releases = list(csv.DictReader(f))
supported = [r for r in releases if not r["status"].startswith("end-of-life")]
with open("supported.csv", "w", encoding="utf-8", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["version", "end_of_support"], extrasaction="ignore")
writer.writeheader()
writer.writerows(supported)
with open("supported.csv", encoding="utf-8", newline="") as f:
print(f.read(), end="")
version,end_of_support
3.15,2031-10
3.14,2030-10
3.13,2029-10
3.12,2028-10
3.11,2027-10
- The list comprehension keeps the five supported versions.
writeheader()writes the column names as the first line.- Our dictionaries have four keys but we asked for two columns.
extrasaction="ignore"skips the extra keys. Without it,DictWriterstops withValueError: dict contains fields not in fieldnames:followed by the extra keys,'status'and'first_released'. Their order in the message can change from run to run.
Why CSV files need newline=””
The csv docs say that without newline="", “on platforms that use \r\n line endings on write an extra \r will be added”. Windows is such a platform. We can copy what happens there by opening the file with newline="\r\n", which turns every \n into \r\n while writing:
import csv
# newline="\r\n" turns every "\n" into "\r\n" when writing: the same thing
# text mode does on Windows when you leave out newline="".
with open("windows_style.csv", "w", encoding="utf-8", newline="\r\n") as f:
writer = csv.writer(f)
writer.writerow(["version", "status"])
writer.writerow(["3.14", "bugfix"])
with open("windows_style.csv", "rb") as f:
print(f.read())
with open("windows_style.csv", encoding="utf-8", newline="") as f:
print(list(csv.reader(f)))
b'version,status\r\r\n3.14,bugfix\r\r\n'
[['version', 'status'], [], ['3.14', 'bugfix'], []]
Every row now ends with \r\r\n, and reading the file gives an empty row [] after each real row. Those are the blank lines people see when they open such a file in a spreadsheet. The docs add that “It should always be safe to specify newline=''“, so always use it for CSV files.
Convert CSV to JSON and JSON to CSV
CSV to JSON: read the rows with DictReader, then save the list with json.dump(). We also add a number, the years of support:
import csv
import json
with open("releases.csv", encoding="utf-8", newline="") as f:
releases = list(csv.DictReader(f))
for release in releases:
release["years"] = int(release["end_of_support"][:4]) - int(release["first_released"][:4])
with open("releases.json", "w", encoding="utf-8") as f:
json.dump(releases, f, indent=2)
with open("releases.json", encoding="utf-8") as f:
lines = f.read().splitlines()
print(len(lines), "lines in releases.json. The first 8:")
print("\n".join(lines[:8]))
44 lines in releases.json. The first 8:
[
{
"version": "3.15",
"status": "bugfix",
"first_released": "2026-10-09",
"end_of_support": "2031-10",
"years": 5
},
JSON to CSV: load the list, take the column names from the first dictionary, and write with DictWriter:
import csv
import json
with open("releases.json", encoding="utf-8") as f:
releases = json.load(f)
print(type(releases).__name__, len(releases), "items, years is", type(releases[0]["years"]).__name__)
fieldnames = list(releases[0].keys())
with open("releases_back.csv", "w", encoding="utf-8", newline="") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(releases)
with open("releases_back.csv", encoding="utf-8", newline="") as f:
for line in f.read().splitlines()[:3]:
print(line)
list 6 items, years is int
version,status,first_released,end_of_support,years
3.15,bugfix,2026-10-09,2031-10,5
3.14,bugfix,2025-10-07,2030-10,5
- In JSON,
yearsstays a number (5, not"5"), because JSON knows numbers and CSV does not. - This simple conversion works for flat data: every row has the same keys and no lists inside.
Try it yourself
Exercise 1: Save students as JSON
Save a list of three students (name and marks) to students.json with indent=2. Load the file again and print the number of students and the average mark.
Exercise 2: Supported until 2030
Read releases.csv with DictReader and print the versions whose end_of_support year is 2030 or later.
Exercise 3: A shopping cart to CSV
Convert this JSON text to cart.csv with the columns item, qty and price: '[{"item": "Notebook", "qty": 2, "price": 150}, {"item": "Pen", "qty": 5, "price": 30}]'.
Solutions
Solution 1
import json
students = [
{"name": "Sara", "marks": 88},
{"name": "Ali", "marks": 75},
{"name": "Hina", "marks": 92},
]
with open("students.json", "w", encoding="utf-8") as f:
json.dump(students, f, indent=2)
with open("students.json", encoding="utf-8") as f:
loaded = json.load(f)
average = sum(s["marks"] for s in loaded) / len(loaded)
print(f"{len(loaded)} students, average {average:.1f}")
3 students, average 85.0
The marks come back as numbers, so sum() works without int().
Solution 2
import csv
with open("releases.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
if int(row["end_of_support"][:4]) >= 2030:
print(row["version"], row["end_of_support"])
3.15 2031-10
3.14 2030-10
CSV values are strings, so we convert the year with int() before comparing.
Solution 3
import csv
import json
cart_json = '[{"item": "Notebook", "qty": 2, "price": 150}, {"item": "Pen", "qty": 5, "price": 30}]'
cart = json.loads(cart_json)
with open("cart.csv", "w", encoding="utf-8", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["item", "qty", "price"])
writer.writeheader()
writer.writerows(cart)
with open("cart.csv", encoding="utf-8", newline="") as f:
print(f.read(), end="")
item,qty,price
Notebook,2,150
Pen,5,30
json.loads() gives a list of dictionaries, which is exactly what writerows() needs.
Common mistakes
- Mixing up
dump/loadanddumps/loads. Thesversions work with strings; the others need an open file. - Writing JSON by hand with single quotes or a last comma. Both raise
JSONDecodeError. Letjson.dumps()write JSON for you. - Calling
json.dump()twice on one file. The docs say JSON “is not a framed protocol”. Our file became{"day": 1}{"day": 2}, andjson.load()failed withExtra data: line 1 column 11 (char 10). Put all items in one list and dump once. - Forgetting
newline=""for CSV files. On Windows this adds blank rows. - Doing maths on CSV values. They are strings:
"150" + "30"is"15030". Convert withint()orfloat()first.
Frequently asked questions
What is the difference between json.dump() and json.dumps()?
json.dumps() returns the JSON as a string. json.dump() writes it straight into an open file. In the same way, json.loads() reads a string and json.load() reads a file.
How do I pretty print JSON in Python?
Pass indent, for example json.dumps(data, indent=2). Each item then goes on its own line, indented by two spaces per level. Add sort_keys=True to sort the keys and ensure_ascii=False to keep letters like é.
Should I use csv or pandas to read a CSV file?
The csv module is built in and is enough for reading, filtering and converting small files. pandas is a separate package for data analysis that you install with pip. Learn csv first, because it shows what a CSV file really contains.
Summary
json.dumps()/json.loads()convert between Python data and JSON strings;json.dump()/json.load()do it with files.indent=2makes JSON readable, andensure_ascii=Falsekeeps letters like é as they are.- Tuples become lists, keys become strings, and sets cannot be saved as JSON.
csv.reader/csv.writerwork with lists;DictReader/DictWriterwork with dictionaries. CSV values are always read as strings.- Open CSV files with
newline=""andencoding="utf-8". CSV to JSON isDictReaderplusjson.dump(); JSON to CSV isjson.load()plusDictWriter.
Next lesson
Next: Lesson 35, Python try, except, else and finally: Handle Errors.
Sources
- json: JSON encoder and decoder (Python docs)
- csv: CSV File Reading and Writing (Python docs)
- What’s New in Python 3.14 (Python docs)
- Python downloads page, Active Python releases (python.org)





