Skip to content
This is my space, where experience meets the will to start over. This is my space, where experience meets the will to start over.

The first step is knowing where you want to go.

  • Home
  • Coding Hub
    • Software & Project
      • Small Biz Ops – S.B.O.
        • SmallBizOps – Day 10/90
      • CRM/ERP
      • MyTracker
      • My Budget
    • Form Zero to “WoW”
      • JavaScript from Zero (Completed)
        • 2. Remove and Edit List Items
        • 3. Separate HTML and JavaScript, Use addEventListener and Conditional Logic
        • 4. Add Dynamic CSS Classes
        • 5. Save & Restore Your List with localStorage
        • 6 – Turn Your App into a Full To-Do List
      • Python from Zero (Completed)
        • 2. Lists & Loops
        • 3. Conditional Menus
        • 4. Edit & Remove Tasks (with closing: Python vs PHP and Large Data)
        • 5 – Save to File: Make Your Tasks Survive Restarts
        • 6 — Pythin from zero – Final Project Polishing: Numbering, Formatting, and Preparing for CSV
      • Rust – From Zero to “WoW” (Completed)
        • 1 – Setup and Project Structure in Rust
        • 2 – User input: validation and error handling
        • 3 – Rust from Zero to “WoW – BMI Calculation and Conditional Logic
        • 4 –Rust – Clear, Formatted Output
        • 5 – Rust – Final Thoughts: Precision as a Form of Respect
      • Go from Zero to “WoW” (Completed)
        • 1 – Why Go Is Perfect for a Personal Expense Tracker
        • 2 – Logging Expenses and Console Input
        • 3 – Go from Zero to “WoW” – Smart Filtering & Display Logic
        • 4 – Go – Saving Data to Local Files
        • 5 – Go – Final Project – Expense Tracker in Go
      • C++ from Zero to “WoW” (Completed)
        • 1 – Why C++ for file organization?
        • 2 – C++ – File Type Detection and Classification
        • 3 – C++ – Creating & Managing Subfolders
        • 4 – C++ – Safe File Movement and User Feedback
        • 5 – C++ – Order as Mental Clarity
      • Ubuntu – From Zero to “WoW” (Completed)
        • 2 – Ubuntu – The Desktop Environment and Essential Commands
        • 3 – Ubuntu – Managing Files, Folders, and Permissions
        • 4 – Ubuntu – Installing and Updating Software with APT and Snap
        • 5 – Ubuntu – Customizing the Desktop Environment
        • 6 – Ubuntu – Network and Device Configuration
        • 7 – Ubuntu – User Management & System Security — “The Cathedral of Permissions”
        • 8 – Ubuntu – The Talking Machine: Terminal & Bash Scripting
        • 9 – Ubuntu – Ubuntu as a Server or Development Environment
        • 10 – Ubuntu – Backup, Maintenance & Troubleshooting
    • Git Hub Repository
      • Small Biz Ops – S.B.O.
      • Mini ERP – PHP & MySQL
      • CleverCRM (Java, Spring Boot)
      • FraudWatch (Python, FastAPI + scikit-learn)
      • OnboardIQ – Smart Onboarding Portal (Flask + SQLite Demo)
    • ArchPilot
      • 1-Users & Roles, End-to-End (Architecture, Database, and Cross-Framework Code)
      • 2 – Client Registry (CRM) Across Frameworks
      • 3 – Project & Budget Tracker (ERP)
      • 4 – Approval Workflow Engine Multi-step routing, status tracking, escalation paths
      • 5 – Audit Trail & Versioning
    • Small Biz Ops – S.B.O.
  • Vivere in USA
  • P4Y
  • Testi poetici
    • 1 – Sospeso
    • 2 – Il bicchiere di vetro quieto
    • 3 – Quando l’amore inciampa
    • 4 – Ma chi siete davvero?
    • 5 – Above the Thread of Day
    • 6 – The Truth That Doesn’t Exist
    • 7 – All of You, I Miss
    • 8 – The Captain and the Ocean
    • 9 – Between Light and Mist
    • 10 – Il peso delle scelte
  • Contact
  • Admin
This is my space, where experience meets the will to start over.
This is my space, where experience meets the will to start over.

The first step is knowing where you want to go.

Coding – Step 10.5 – Python form Zero – Save to File: Make Your Tasks Survive Restarts

Posted on 23 Agosto 202523 Agosto 2025 By Francesco

In this penultimate lesson we bring persistence to our To-Do App: saving tasks to a .txt file and loading them automatically when the program starts again.

In previous lessons we built a small To-Do App in Python with add, edit, and remove functionality. But every time we closed the program, all tasks were lost. In this step we solve that problem by adding data persistence with a plain text file.

Why Save to a File?

Without persistence, the app is only useful while it’s running. Users expect their tasks to be there when they come back. Common persistence options are:

  • Plain text file (.txt) — simplest option (what we use here).
  • Structured formats — JSON or CSV.
  • Databases — SQLite, MySQL, PostgreSQL, etc.

This step uses a plain .txt file for clarity and simplicity.

1) Write Tasks to a .txt File

tasks = ["Buy milk", "Finish project", "Read a book"]

with open("tasks.txt", "w", encoding="utf-8") as f:
    for task in tasks:
        f.write(task + "\n")

print("Tasks saved!")

Notes: "w" overwrites the file each time; encoding="utf-8" avoids issues with special characters; and the with statement ensures the file closes properly.

2) Load Tasks at Startup

loaded = []
try:
    with open("tasks.txt", "r", encoding="utf-8") as f:
        loaded = [line.strip() for line in f]
    print("Loaded:", loaded)
except FileNotFoundError:
    print("No saved tasks yet.")

3) Full Example — To-Do App with Save/Load

Here is the complete CLI app with add / edit / remove plus automatic save/load. It saves on every change and once again when quitting.

from typing import List

FILENAME = "tasks.txt"


# ---------- Persistence Layer ----------
def load_tasks(filename: str = FILENAME) -> List[str]:
    tasks: List[str] = []
    try:
        with open(filename, "r", encoding="utf-8") as f:
            for line in f:
                task = line.strip()
                if task:
                    tasks.append(task)
    except FileNotFoundError:
        pass
    return tasks


def save_tasks(tasks: List[str], filename: str = FILENAME) -> None:
    with open(filename, "w", encoding="utf-8") as f:
        for task in tasks:
            f.write(task + "\n")


# ---------- Helpers ----------
def print_tasks(tasks: List[str]) -> None:
    if not tasks:
        print("\n[No tasks yet]\n")
        return
    print("\nCurrent tasks:")
    for i, t in enumerate(tasks, start=1):
        print(f"  {i}. {t}")
    print()


def add_task(tasks: List[str]) -> None:
    new_task = input("Enter new task: ").strip()
    if not new_task:
        print("Empty task not added.")
        return
    tasks.append(new_task)
    save_tasks(tasks)
    print("Task added and saved.")


def remove_task(tasks: List[str]) -> None:
    print_tasks(tasks)
    if not tasks:
        return
    idx_str = input("Enter the task number to remove: ").strip()
    if not idx_str.isdigit():
        print("Please enter a valid number.")
        return
    idx = int(idx_str)
    if 1 <= idx <= len(tasks):
        removed = tasks.pop(idx - 1)
        save_tasks(tasks)
        print(f"Removed: '{removed}' (saved).")
    else:
        print("Invalid task number.")


def edit_task(tasks: List[str]) -> None:
    print_tasks(tasks)
    if not tasks:
        return
    idx_str = input("Enter the task number to edit: ").strip()
    if not idx_str.isdigit():
        print("Please enter a valid number.")
        return
    idx = int(idx_str)
    if 1 <= idx <= len(tasks):
        current = tasks[idx - 1]
        print(f"Current: {current}")
        new_text = input("Enter the new text: ").strip()
        if not new_text:
            print("Empty text — task unchanged.")
            return
        tasks[idx - 1] = new_text
        save_tasks(tasks)
        print("Task updated and saved.")
    else:
        print("Invalid task number.")


# ---------- CLI ----------
def main() -> None:
    print("=== Step 10.6 — Save to File ===")
    tasks = load_tasks()
    print(f"Loaded {len(tasks)} task(s).")
    while True:
        print_tasks(tasks)
        print("Choose an action:")
        print("[a] Add  [e] Edit  [r] Remove  [q] Quit")
        choice = input("> ").strip().lower()

        if choice == "a":
            add_task(tasks)
        elif choice == "e":
            edit_task(tasks)
        elif choice == "r":
            remove_task(tasks)
        elif choice == "q":
            save_tasks(tasks)
            print("Tasks saved. Goodbye!")
            break
        else:
            print("Unknown option. Please choose a, e, r, or q.")


if __name__ == "__main__":
    main()

Python vs PHP (Quick Compare)

  • Python: very concise file I/O (open, with, read/write), excellent for learning fundamentals.
  • PHP: similar primitives (fopen, fwrite, fgets), but in web apps you usually move to databases or JSON for scalability.

What’s Next (Step 10.7)

In the final lesson we’ll improve persistence using JSON, which allows us to store richer data such as status, due date, or priority. You’ll see how simple it is to switch formats while keeping clean app logic.

Homework:

  1. Add a [l] “List” command that prints tasks without other actions.
  2. Show a clear message if the user tries to remove or edit an out-of-range index.
  3. Prevent duplicates: if the user adds a task that already exists, skip or ask confirmation.
  4. Also save the last modified date/time next to the task (still using .txt).

Tags: #Python #BeginnerFriendly #FileHandling #ToDoApp #ProgrammingBasics #Persistence #LearnToCode

Post Views: 322

Condividi:

  • Condividi su Facebook (Si apre in una nuova finestra) Facebook
  • Condividi su X (Si apre in una nuova finestra) X
Python Coding Data PersistenceFile HandlingLearn to CodeProgramming BasicsPythonPython TutorialSave to FileTo-Do App

Navigazione articoli

Previous post
Next post

Francesco

My name is Francesco Boschi, originally from Italy and currently based in the United States. For over twenty years, I’ve worked as a manager and consultant across diverse sectors — from education and cultural institutions to the food industry — developing skills in operational management, strategic consulting, and complex problem-solving. In recent years, I’ve combined this experience with a strong passion for software development, creating custom tools designed to simplify workflows and meet real business needs.

Relocating to the U.S. marks the beginning of a new chapter: a personal and professional decision driven by the desire to be close to my son and to embrace new challenges in a different environment. Today, my goal is to turn my experience into meaningful solutions, blending strategic vision with technical expertise to help people and organizations work more effectively.

I enjoy moving between different worlds, adapting tools and approaches to people and contexts. I bring leadership, flexibility, attention to detail, analytical thinking, and a strong problem-solving mindset — along with a deep curiosity to learn and grow. Above all, I believe in sharing: I’m always eager to offer my experience to support the growth of others.

Related Posts

Python

Coding – Step 10 – Python from Zero – Lesson 1: Variables, Input, and Simple Logic

Posted on 28 Luglio 202523 Agosto 2025

Welcome to the first real Python lesson — where you’ll build a mini console app using real code, logic, and user input. No theory-only content here: we learn by writing and running code immediately. 📚 What You’ll Learn ✅ How to use print() and input()✅ How to store and use…

Condividi:

  • Condividi su Facebook (Si apre in una nuova finestra) Facebook
  • Condividi su X (Si apre in una nuova finestra) X
Read More

SmallBizOps – Day 10/90

Posted on 14 Febbraio 202614 Febbraio 2026

In just 10 days, SmallBizOps evolved from a blank page into a fully functional inventory management module — complete with stock movement tracking, low-stock alerts, audit trails, and structured operational logic. Built in public using Laravel and MySQL, it demonstrates real-world ERP architecture focused on accountability, reliability, and business control — not just features.

Condividi:

  • Condividi su Facebook (Si apre in una nuova finestra) Facebook
  • Condividi su X (Si apre in una nuova finestra) X
Read More
Coding

Coding Step 12.4 Go – Saving Data to Local Files

Posted on 12 Ottobre 202512 Ottobre 2025

Learn how to save, load, and back up your expenses locally in Go — from CSV to JSON — with simple, reliable, and human code. The “wow” lies in how trust and simplicity work together.

Condividi:

  • Condividi su Facebook (Si apre in una nuova finestra) Facebook
  • Condividi su X (Si apre in una nuova finestra) X
Read More

Iscriviti alla nostra Newsletter

🤞 Let's keep in touch

We do not send spam! Read our Privacy policy for more information.

Controlla la tua casella di posta o la cartella spam per confermare la tua iscrizione

Cerca nel sito

©2026 This is my space, where experience meets the will to start over. | WordPress Theme by SuperbThemes