Codiqo

Learn Python · lesson 40 of 60 · about 10 minutes

Project: Journal

Keep Sam's journal in a file: read it if it's there, add new entries, and read it back safely.

What you'll learn

  • Append entries to a file
  • Read entries back with numbers
  • Handle a missing file

Sam's journal

Sam wants to keep a journal that grows a little every day. The assistant first tries to read journal.txt to say how many entries it already has; the very first time there's no file, so except FileNotFoundError says a new journal is starting instead of crashing. Then it opens the file with "a", so old entries are kept, and adds every entry Sam types until a blank line. Finally it reads the whole file back to count the entries and find the longest one.

The plan

Two functions do the work:

  • add_entry(text) appends a line to journal.txt
  • show_entries() prints every entry with a number, or a friendly message if there's no journal yet

The main loop reads commands until the user types quit.

The journal

FILE = "journal.txt"

def add_entry(text):
    with open(FILE, "a") as f:
        f.write(text + "\n")

def show_entries():
    try:
        with open(FILE) as f:
            for i, line in enumerate(f, 1):
                print(f"{i}. {line.strip()}")
    except FileNotFoundError:
        print("No entries yet")

show_entries()
while True:
    entry = input("> ")
    if entry == "quit":
        break
    add_entry(entry)
show_entries()

Output

No entries yet
> > > 1. Learned try/except
2. Wrote my first file

Tip

Real apps add a date to each entry. Python's datetime module can do that, which you'll meet in the next unit.

A file that isn't there yet

Opening a file to read it fails if it doesn't exist, but opening it with "a" creates it. So the read goes inside try, with except FileNotFoundError for the first run, and the appending needs no try at all.

The first run

try:
    with open("diary.txt") as f:
        print(f"{len(f.readlines())} entries so far")
except FileNotFoundError:
    print("No diary yet")
with open("diary.txt", "a") as f:
    f.write("Day one\n")
with open("diary.txt") as f:
    print(f"{len(f.readlines())} entries so far")

Output

No diary yet
1 entries so far

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.