Project: catalogue search
Last updated
Time to put Stage 2 together. You'll build the library's catalogue: a program that loads books from a CSV file, answers commands to list, find and add books, turns bad input into a clear message, saves the catalogue as JSON, and comes with tests that prove it works.
By the end of this lesson you can
- Plan a program that reads, searches, changes and saves data
- Load the rows of a CSV file into a list of dicts, and save them as JSON
- Turn bad input into a clear message instead of a crash
- Split a program into a module and a main file, and test the module's functions
Plan it
Here's the plan, in plain words first.
What the program does: it loads the library's books from a file called books.csv. Then it asks for commands, one per line, until it's told to quit:
listprints every book.findfollowed by some words prints the books whose title or author contains them, whatever the capitals.addasks for a title, an author and a year, and adds the book. Bad answers get a message, not a crash.
When it quits, it saves every book, the new ones too, to catalogue.json. Here's a session with the finished program:
Catalogue: 5 books. Commands: list, find <words>, add, quit > list Dune Frank Herbert 1965 Emma Jane Austen 1815 Beloved Toni Morrison 1987 Matilda Roald Dahl 1988 The Hobbit J. R. R. Tolkien 1937 > find tolkien The Hobbit J. R. R. Tolkien 1937 1 found > add Title: Emma Author: Year: 1815 Not added: a book needs a title and an author. > add Title: Persuasion Author: Jane Austen Year: 1817 Added Persuasion. > find austen Emma Jane Austen 1815 Persuasion Jane Austen 1817 2 found > lend Dune Unknown command: lend. Commands: list, find <words>, add, quit > quit Saved 6 books to catalogue.json.
The pieces, and the lesson each comes from:
- Each book is a dict, like
{"title": "Dune", "author": "Frank Herbert", ...}, and the catalogue is a list of them (lessons 2.1 and 2.2). csv.DictReaderreads the file into those dicts, andjson.dumpsaves them (2.8).findis one comprehension (2.4).- Bad input raises a
ValueErrorthat the command loop catches (2.6). - At the end the functions move into their own module,
catalogue.py, with tests (2.7 and 2.10).
Books as dicts from books.csv
Start with the data. The books.csv tab shows the file: a header line naming the columns, then one book per line.
csv.DictReader turns each line after the header into a dict, using the header's names as keys. Everything in a CSV file is text, so load_books turns the year and the number of copies into numbers as it goes. Do that once, when the data comes in, and the rest of the program can trust it.
Open the books.csv tab, add a line for a sixth book, and run it again.
Commands: list and find
Now the loop that answers commands. Each command is one line of input, like find aust, and the program needs the first word apart from the rest.
.partition(" ") splits text at the first space and gives back three things: the part before it, the space itself and the part after it. The space isn't needed, so its name is _, which is Python's way of saying "I'm ignoring this". Text with no space gives back the whole text and two empty strings.
find keeps the books whose title or author contains the words. It's one list comprehension from lesson 2.4, and .lower() on both sides makes ZZZ, zzz and Zzz all the same.
The input box has four commands, one per line. Run it, then change them.
Type a command the program doesn't know, like lend Dune, and run it. Nothing happens at all, which leaves the user guessing. The next step fixes that.
Adding, and bad input
Users type things you don't expect. The add command asks for three answers, and any of them can be wrong: an empty title, or soon for the year.
The checking goes in its own function, make_book. If an answer is bad, it raises a ValueError with a message saying what's wrong, as in lesson 2.6. If all is well, it returns the new book. The loop calls it inside try, and except ValueError as e catches the error and prints its message. The else part runs only when nothing was raised, so a bad book never reaches the list.
Two more fixes: find with no words asks what to find, and an unknown command gets a message that lists the commands.
Why not just call int(year) and catch its ValueError? You could. make_book does its own checks so it can give a message in the library's words, and so it can be tested on its own in step 6.
Save to JSON
Books added in a session are lost when the program ends, unless it saves them. save_books writes the whole list to catalogue.json with json.dump. indent=2 puts each key on its own line, so the file is easy to read.
The last two lines run after the loop ends, when the user types quit. Run it: the file the program wrote appears under the output.
Why save as JSON and not back to CSV? JSON keeps the types: 1965 is saved as a number, so loading it again needs no int(). And in Stage 3, when a book grows a list of loans, JSON can hold lists inside a book, where CSV can't.
A module, and tests
The program is getting long. The functions that work on books, load_books, save_books, line, find and make_book, now move into their own file, catalogue.py, as in lesson 2.7. They don't change at all. The main program will only handle the commands.
Functions that don't ask for input or print are easy to test: give them values, and check what comes back. Here are tests in the pytest style from lesson 2.10. In a real project they'd be in test_catalogue.py, and running pytest would find and run every test_ function. The page has no pytest, so the last lines call them by hand.
Now break something on purpose. In the catalogue.py tab, take .lower() off text = text.lower() in find, and run the tests again. test_find_ignores_case fails with an AssertionError, and the tests after it don't run. The test caught a bug before any user did.
The finished catalogue
Here's the whole program: main.py handles the commands, and the catalogue.py tab has the functions. The loop is inside a function, main, and the last two lines run it only when this file is the one being run, as lesson 2.7 showed. That way the tests can import from the program without starting it.
Run it, then Watch it run and follow one command from the input box to the output.
Some things to try:
- Add a
countcommand that prints how many books there are. - Make
findalso match the year, sofind 1988works. Remember the year is a number:str(b["year"]). - Add a test for it to the tests in step 6, run them, and watch the new test pass.
That's Stage 2 done: your programs can now read and save files, survive bad input, and prove they work. But look at what a book is: a dict, where a typo like book["titel"] is a KeyError, and nothing stops a book being given a negative number of copies. Stage 3 starts there, and replaces the dicts with objects.
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.
- The Python Standard Library: csv, DictReader: each row as a dict, keyed by the header line
- The Python Standard Library: json.dump: writing data as JSON, with indent
- Built-in Types: str.partition
- Built-in Types: str.isdigit
- The Python Tutorial: Handling Exceptions: try, except … as, and else
- The Python Tutorial: Executing modules as scripts: if __name__ == "__main__"