Bigger programs · lesson 8 of 12
Parts in this lesson
Awith open(name) as f:opens, then closes
Bfor line in fa line at a time
C"w" "a"write, add
Dcsv.DictReaderrows as dicts
Ejson.dump json.loadsave and load data

Files, CSV and JSON

Last updated

So far everything a program knew was lost when it ended. In this lesson you'll read text files, write and add to them, read a spreadsheet saved as CSV, save your data as JSON and load it back, and read the error you get when a file isn't where you said.

By the end of this lesson you can

  • Open a file with with open(...), and read it whole or a line at a time
  • Write a file, and add to the end of one
  • Read rows from a CSV file with csv.DictReader
  • Save lists and dicts as JSON and load them back

Opening a file

A file keeps data after the program ends. This step has a text file beside the program, welcome.txt; click its tab to see it.

open("welcome.txt", encoding="utf-8") opens the file and gives back a file object, here named f. Its .read() method gives the whole file as one piece of text. encoding="utf-8" says how the file's characters are stored as bytes; UTF-8 is what almost every file uses today, so always say it.

Step 1 code
Edit the code, then run it again

with opens the file for the lines indented under it, and closes it when they end, even if one of them stops with an error. An open file holds on to something the computer has only so much of, so always open files with with.

The blank line in the output isn't a mistake. The file ends with a newline, print adds its own, and that makes two. The 57 counts every character, newlines included.

A line at a time

A file object works with for, like a list: each round gives the next line of the file. Each line still ends with its newline, so .strip() from lesson 1.5 takes it off.

Step 2 code
Edit the code, then run it again

Reading a line at a time is how you handle a big file: only one line is held in memory at once. Add a fifth title to titles.txt and run it again.

Writing a file

The second thing you give open is the mode. Without one, the file is opened for reading. "w" opens it for writing: Python makes the file if it isn't there, and empties it if it is. "a" opens it for adding to the end, called appending.

f.write() writes text exactly as given. Unlike print, it doesn't add a newline, so line 5 adds "\n" itself.

Step 3 code main.py
Edit the code, then run it again

Under the output, the page shows loans.txt, the file the program wrote. Now see what "w" does to a file that's already there. Press Run:

Step 3 code main.py
Edit the code, then run it again

Only Emma is left. The second open with "w" emptied the file before writing. Use "a" when you mean to add, and "w" only when you mean to replace the whole file.

Spreadsheets: CSV

A CSV file, short for comma-separated values, is a table saved as text: one row per line, commas between the columns. Every spreadsheet program can save one. Click the books.csv tab: the first row names the columns.

The csv module reads it. csv.DictReader reads each row as a dict, with the first row's names as the keys, so row["title"] is that row's title.

Step 4 code
Edit the code, then run it again

Two things to notice. Every value comes back as text, even 2, so line 6 uses int(). And the third title has commas in it, so the file wraps it in quotes. Splitting each line on commas yourself would break that title into three; the csv module gets it right. Open CSV files with newline="", as the csv module's documentation asks, so it can handle line endings itself.

To write a CSV file, the module has csv.writer and csv.DictWriter, which work the same way in reverse.

Saving data: JSON

CSV suits a flat table. For lists and dicts, including dicts inside a list, use JSON. It's a text format that looks almost like Python's own, and nearly every language can read it.

json.dump(books, f) writes the data to an open file. json.load(f) reads it back as lists and dicts. indent=2 lays the file out on several lines so a person can read it.

Step 5 code main.py
Edit the code, then run it again

Look at books.json under the output. JSON writes True as true, False as false and None as null, and json.load turns them back. Line 14 prints True: what came back equals what went in. That's how a program can stop and start again without losing anything.

JSON keeps text, whole numbers, decimals, True, False, None, lists and dicts with text keys. A date has to be saved as text, like "2026-12-18" on line 4.

A file that isn't there

The file beside this program is books.csv. Press Run and read the error.

Step 6 code
Edit the code, then run it again

FileNotFoundError: No such file or directory: 'book.csv'. Line 3 asks for book.csv, without the s. Python looks for the name in the folder the program runs in, and it must match exactly. Fix the name on line 3 and run it again.

On your own computer, this error also appears when the program is run from a different folder than the file is in. In lesson 2.6 you saw how try and except FileNotFoundError let a program carry on, for example by starting with an empty catalogue.

Check what you learned

Four questions. Pick or type an answer, then check it.

A file already holds Dune. What is in it after open("loans.txt", "a", encoding="utf-8") and f.write("Emma\n")?
Why open files with with?
A CSV row has copies of 3. What is row["copies"] after csv.DictReader reads it?
Python's None is saved by json.dump as what?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Python