Python Project: A Reading List Manager
A reading list manager is a program that keeps track of books to read. It saves the list in a file, so the books are still there on the next run.
A missing file starts empty
The try opens a file that is not there. The except then starts with an empty list.
try:
f = open("books_missing.txt", "r")
books = f.read().splitlines()
f.close()
except FileNotFoundError:
books = []
print("Books:", books)Save books, then load them
The first open writes two books, one per line. The second open reads them back into a list.
f = open("reading_list.txt", "w")
f.write("Dune\n")
f.write("Pride and Prejudice\n")
f.close()
f = open("reading_list.txt", "r")
books = f.read().splitlines()
f.close()
print(books)Add a book and save again
The program loads the list, appends one book, and writes the whole list back.
f = open("reading_list.txt", "w")
f.write("Dune\n")
f.close()
f = open("reading_list.txt", "r")
books = f.read().splitlines()
f.close()
books.append("The Hobbit")
f = open("reading_list.txt", "w")
for book in books:
f.write(book + "\n")
f.close()
print(books)Example
f = open("my_books.txt", "w")
f.write("Dune\n")
f.write("The Hobbit\n")
f.close()
try:
f = open("my_books.txt", "r")
books = f.read().splitlines()
f.close()
except FileNotFoundError:
books = []
books.append("Pride and Prejudice")
f = open("my_books.txt", "w")
for book in books:
f.write(book + "\n")
f.close()
print("Reading list:")
for i, book in enumerate(books, start=1):
print(i, book)
print("Total books:", len(books))Key points
- Reading list: the books a reader plans to read, kept in a file
- Use try/except to load the file, and start with an empty list when the file is missing
- Use open() with "w" to save the list, one book per line
- Use open() with "r" and read().splitlines() to load the list back
- Add a book with append(), then save the whole list
- Print the list with numbers, so each book has its place
In this example, the program writes my_books.txt first, with two books inside. The try then loads the file back into a list. The program appends a third book and saves the whole list again. The numbered printout shows all three books in order. The total of 3 proves the new book was saved with the rest.
Note
Saving the whole list each time is simple and safe for a short list.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What happens when the saved file is missing?