Mini-Project: Todo App
Before you start
#What you'll build
todos.txt automatically so when you reopen the app tomorrow, your todos are still there.Sample interaction
Todo App
1. add 2. list 3. done 4. quit
Choose: 1
Task: buy milk
1. add 2. list 3. done 4. quit
Choose: 1
Task: write blog post
1. add 2. list 3. done 4. quit
Choose: 2
[ ] 1. buy milk
[ ] 2. write blog post
1. add 2. list 3. done 4. quit
Choose: 3
Which task number? 1
1. add 2. list 3. done 4. quit
Choose: 2
[x] 1. buy milk
[ ] 2. write blog post
1. add 2. list 3. done 4. quit
Choose: 4
Saved. Bye!
#What you'll learn
After this lesson, you will be able to:
- Read and write text files with open() and the with statement
- Model a program's state as a list of dicts
- Build a menu loop that keeps running until the user chooses to quit
#Step 1: A list of todos in memory
text and done.todos = []
todos.append({"text": "buy milk", "done": False})
todos.append({"text": "write blog post", "done": False})
for i, t in enumerate(todos, start=1):
mark = "x" if t["done"] else " "
print(f"[{mark}] {i}. {t['text']}")enumerate(seq, start=1) numbers items starting at 1 instead of 0 — the right choice for human-facing lists.What does this print? items = ["a", "b", "c"] for i, x in enumerate(items): print(i, x)
Why model each todo as a dict instead of just a string?
#Step 2: Menu loop
while True loop, an if/elif chain on the user's choice, and a break for quit.This code calls input(). Python here can't pause to ask you, so type the answers below before running — one value per line, in the order the program asks for them.
todos = []
while True:
print("\n1. add 2. list 3. done 4. quit")
choice = input("Choose: ").strip()
if choice == "1":
text = input("Task: ").strip()
todos.append({"text": text, "done": False})
print("Added.")
elif choice == "2":
for i, t in enumerate(todos, start=1):
mark = "x" if t["done"] else " "
print(f"[{mark}] {i}. {t['text']}")
elif choice == "3":
n = int(input("Which task number? "))
todos[n - 1]["done"] = True
print("Marked done.")
elif choice == "4":
print("Bye!")
breakint(input(...)) - 1 converts the human-friendly number (1-based) back to the Python index (0-based). Run this — you have a working in-memory todo app already.What happens? todos = [{"text": "buy milk", "done": False}] todos[0]["done"] = True print(todos[0]["done"])
dict[key] = new_value. The dict inside the list is the same dict before and after; we just modified its "done" value. Compare with tuples, which are immutable: (1, 2)[0] = 99 raises TypeError. This is also why mutable objects (lists, dicts, sets) can be shared via aliasing — modifying through one reference is visible through all references that point to the same object.#Step 3: Save to a file
open(path, "w") to write and open(path, "r") to read. The with statement ensures the file is closed even if an error happens mid-write.def save(todos, path="todos.txt"):
with open(path, "w") as f:
for t in todos:
mark = "x" if t["done"] else "o"
f.write(f"{mark}|{t['text']}\n")x|task text (done) or o|task text (not done). The | is a delimiter — a tiny custom format that's easy to parse back.Why use `with open(...) as f:` instead of plain `f = open(...)`?
#Step 4: Load from a file
On startup, read the file and rebuild the list. Handle the "file doesn't exist yet" case so first-run users don't crash.
import os
def load(path="todos.txt"):
if not os.path.exists(path):
return []
todos = []
with open(path, "r") as f:
for line in f:
line = line.rstrip("\n")
if not line:
continue
mark, text = line.split("|", 1)
todos.append({"text": text, "done": mark == "x"})
return todosline.split("|", 1) splits at most ONCE, so even if the task text contains a |, only the first one separates the mark from the body. That's the kind of edge case worth thinking about up front.What happens if todos.txt does not exist? with open("todos.txt", "r") as f: content = f.read()
"r") does NOT create files — if the path doesn't exist, Python crashes. Write mode ("w") and append mode ("a") DO create the file if missing, but they treat existing files very differently ("w" overwrites, "a" appends). Three ways to handle missing files: check first with os.path.exists(path), catch the exception with try/except FileNotFoundError, or use pathlib.Path(path).read_text() then catch. The catch pattern is most Pythonic ("ask forgiveness, not permission").#Step 5: Wire it all together
Load on startup. Save on every change (or only on quit — your choice).
This code calls input(). Python here can't pause to ask you, so type the answers below before running — one value per line, in the order the program asks for them.
import os
PATH = "todos.txt"
def load():
if not os.path.exists(PATH):
return []
todos = []
with open(PATH, "r") as f:
for line in f:
line = line.rstrip("\n")
if line:
mark, text = line.split("|", 1)
todos.append({"text": text, "done": mark == "x"})
return todos
def save(todos):
with open(PATH, "w") as f:
for t in todos:
mark = "x" if t["done"] else "o"
f.write(f"{mark}|{t['text']}\n")
def main():
todos = load()
print("Todo App")
while True:
print("\n1. add 2. list 3. done 4. quit")
choice = input("Choose: ").strip()
if choice == "1":
text = input("Task: ").strip()
todos.append({"text": text, "done": False})
save(todos)
elif choice == "2":
for i, t in enumerate(todos, start=1):
mark = "x" if t["done"] else " "
print(f"[{mark}] {i}. {t['text']}")
elif choice == "3":
n = int(input("Which task number? "))
todos[n - 1]["done"] = True
save(todos)
elif choice == "4":
save(todos)
print("Saved. Bye!")
break
main()That's a complete, persistent todo app — in 35 lines of Python.
#Now build it yourself
input() reads from the Input box: type every answer there, one per line, before you press Run.Full Todo App with file persistence
Build a CLI todo app with four commands: add, list, done, quit. State is a list of dicts with `text` and `done` keys. Keep the logic in five small functions: `load(path)`, `save(todos, path)`, `add_task(todos, text)`, `mark_done(todos, number)` (the number is 1-based, as shown in the list) and `render(todos)` (returns the list lines such as `[x] 1. buy milk`). Persist to `todos.txt` so todos survive between runs. Use `with open(...)` for both reading and writing, and handle the case where the file does not exist yet. Type the inputs, one per line, in the Input box above Run.
Todo App
1. add 2. list 3. done 4. quit
Choose: 1
Task: buy milk
1. add 2. list 3. done 4. quit
Choose: 2
[ ] 1. buy milk
1. add 2. list 3. done 4. quit
Choose: 3
Which task number? 1
1. add 2. list 3. done 4. quit
Choose: 2
[x] 1. buy milk
1. add 2. list 3. done 4. quit
Choose: 4
Saved. Bye!This code calls input(). Python here can't pause to ask you, so type the answers below before running — one value per line, in the order the program asks for them.
#Now make it your own
Try one of these variations:
- Delete a task. Add a "remove" option that pops a task by its number. Re-number the rest automatically since lists shift after
pop(). - Categories. Let each task have a category (
work,home,errands). Filter the list view by category. - JSON storage. Swap the custom
|-delimited format forjson.dump(todos, f)andjson.load(f). Cleaner, no parser needed, and you can add new fields without breaking the file format.
#What's next
load/save can live in one file, the menu logic in another, and you'll start to feel what Python "projects" actually look like.