Python · Module 14 · Lesson 11 min read

CLI To-Do App

Project goal

A command-line to-do list that remembers tasks between runs by saving them to a JSON file.

Skills you'll combine

Functions, lists of dicts, loops, match, file handling with pathlib, JSON, and error handling.

Design

  • Data: a list of tasks like {"id": 1, "title": "Learn Python", "done": false}
  • Storage: load_tasks() / save_tasks() read and write todos.json
  • Commands: add <title>, list, done <id>, delete <id>, quit

Steps

  1. Write load_tasks() so it returns [] if the file doesn't exist yet.
  2. Write one small function per command.
  3. Add a loop that reads a command and dispatches it with match.
  4. Handle bad input (unknown command, missing id) without crashing.

Ideas to extend it

Due dates with datetime, priorities, sorting, a search command, or colours with the rich library.

▶️ Runs in the app: put commands in the Input box, one per line (e.g. add Learn Python, list, done 1, quit).

Example

Python
import json
from pathlib import Path

FILE = Path("todos.json")

def load_tasks():
    if not FILE.exists():
        return []
    return json.loads(FILE.read_text(encoding="utf-8"))

def save_tasks(tasks):
    FILE.write_text(json.dumps(tasks, indent=2), encoding="utf-8")

def add(tasks, title):
    new_id = max((t["id"] for t in tasks), default=0) + 1
    tasks.append({"id": new_id, "title": title, "done": False})
    print(f"Added #{new_id}: {title}")

def show(tasks):
    if not tasks:
        print("No tasks yet 🎉")
    for t in tasks:
        print(f"[{'x' if t['done'] else ' '}] {t['id']}. {t['title']}")

def mark_done(tasks, task_id):
    for t in tasks:
        if t["id"] == task_id:
            t["done"] = True
            return print(f"Completed #{task_id}")
    print(f"No task #{task_id}")

def main():
    tasks = load_tasks()
    while True:
        try:
            command, _, arg = input("> ").strip().partition(" ")
        except EOFError:
            break
        match command:
            case "add" if arg:
                add(tasks, arg)
            case "list":
                show(tasks)
            case "done" if arg.isdigit():
                mark_done(tasks, int(arg))
            case "quit":
                break
            case _:
                print("Commands: add <title> | list | done <id> | quit")
        save_tasks(tasks)

main()

# Input box:
# add Learn Python
# add Build a project
# done 1
# list
# quit