Files, CSV & JSON in Python
Chapter 20: Files, CSV & JSON
7 short lessons, with 3D animations, quizzes and coding tasks.
The lessons
Reading files
with open(name) as f: opens a file for reading and closes it automatically when the block ends, and every read continues from a cursor where the last read stopped.
Writing and adding to files
open(name, "w") starts the file empty and writes from the beginning, open(name, "a") keeps what's there and adds to the end, and f.write(text) writes exactly the text you give it.
CSV files
A CSV file stores a table as lines of comma-separated values, and csv.reader turns each line into a list of strings (or csv.DictReader into a dictionary).
JSON
json.dump/json.dumps turn Python dictionaries and lists into JSON text, and json.load/json.loads turn JSON text back into Python data.
Paths and folders: pathlib
pathlib.Path turns a path into an object you can join with /, take apart (name, extension, folder), check, read, write, and use to list a folder.
Text and encodings: Unicode, UTF-8 and bytes
A str is a row of Unicode characters; to save or send it, Python encodes it into bytes with an encoding, and decodes bytes back with the same one, and the one to use is UTF-8, so always write encoding="utf-8" when you open a text file.
Project: a contacts book saved to JSON
Your phone remembers every contact you've saved, even after it's switched off and on again. A program, though, forgets everything the moment it ends: its dictionaries live only in memory. To remember, it has to save its data to a file before it ends and load it again next time. In this project you'll build a small contacts book that does exactly that. It uses everything from World 3: functions, errors, and files with JSON. The plan in one sentence: load the contacts from a JSON file (or start empty), carry out commands one by one, then save the contacts back to the file. Its words: persistence: data that survives after the program ends, because it was saved to a file command: one line the user types, like add Joy 01933-333333, find Rimi, delete Bo, list or quit load / save: read the file into a dictionary at the start; write the dictionary back at the end Step by step, the plan: 1. Load: loadcontacts reads contacts.json; if the file isn't there yet, it returns {} instead of crashing. 2. **Handle**: handle(line, contacts) carries out one command and **returns** the message to show. 3. **Loop**: read commands until quit, printing each message. 4. **Save**: savecontacts writes the dictionary back as JSON. Here are the commands working on the contacts dictionary: Step 1: load and save. A missing file isn't a bug: it just means nobody has saved anything yet. So loadcontacts catches **only** FileNotFoundError (Lesson 18.1) and returns an empty dictionary. Saving uses indent=2, so the file is easy for a person to read and check. **Step 2: one function per command line.** handle splits the line into words: the first is the command, the rest are its details. It **returns** a message instead of printing it, so it can be tested on its own, with any dictionary, without typing anything (Lesson 14.3). Each command is one small dictionary job: contacts[name] = number, contacts.get(name, ...), del contacts[name], and sorted(contacts) for the list. **Why build it this way, and what it costs.** Each piece has one job and a clear name, so each can be tested and fixed on its own: a wrong message is a bug in handle, a lost contact is a bug in saving. Every command is a dictionary operation that takes about the same time however many contacts there are; only list walks them all (and sorts them). Loading and saving read and write the whole file once per run. **Mistakes and edge cases.** **Catching every error in load.** except Exception: would also hide a broken JSON file, and the program would then save {} over it, deleting every contact. Catch only FileNotFoundError. **Forgetting to save.** Changes made in the loop are lost if the program ends before savecontacts. A command with the wrong number of words. add Joy (no number) shouldn't crash; handle checks len(parts) and answers "Unknown command". Names with spaces. add Rimi Akter 0171... has four words; this simple version keeps names to one word.