Creating a Simple Python To-Do List Manager

Introduction In today's fast-paced world, managing tasks efficiently is essential. A to-do list manager helps us stay organized, ensuring nothing slips through the cracks. In this article, we’ll build a simple command-line to-do list manager using Python. This program will allow users to add tasks, list them, mark them as done, delete them, and save the list for future use—all with basic Python features. Why a To-Do List Manager? A to-do list manager is invaluable for: Organizing daily tasks. Prioritizing what needs to be done. Tracking completed tasks. Ensuring nothing is forgotten. Our program will be a basic version, easy to expand with additional features, making it ideal for beginners and practical for daily use. Design and Planning Our to-do list manager will run in the command line, with users interacting via simple commands. The supported commands are: add [task]: Add a new task. list: Display all tasks, with completed ones marked as [x]. done [task_number]: Mark a specific task as completed. delete [task_number]: Remove a specific task. quit: Exit the program and save the current list to a file. Tasks will be stored in a list in memory, saved to a file upon exit, and loaded from the file when the program starts. We’ll use a simple text file for storage, with each task on a new line and completed tasks prefixed with [x]. Implementation Here’s the step-by-step implementation of the code, with explanations for each part. Step 1: Import Required Modules import os We need the os module to check if the file exists. Step 2: Define the File Name for Saving Tasks TODO_FILE = "todo.txt" A constant TODO_FILE defines the name of the file where tasks will be stored. Step 3: Function to Load Tasks def load_tasks(): tasks = [] if os.path.exists(TODO_FILE): with open(TODO_FILE, "r") as file: for line in file: tasks.append(line.strip()) return tasks The load_tasks() function checks if the file exists. If it does, it reads each line as a task into a list and returns it. If not, it returns an empty list. Step 4: Function to Save Tasks def save_tasks(tasks): with open(TODO_FILE, "w") as file: for task in tasks: file.write(task + "\n") The save_tasks(tasks) function writes the task list to the file, one task per line. Step 5: Main Function to Handle User Interaction def main(): tasks = load_tasks() while True: print("\nTo-Do List Manager") print("Commands:") print(" add [task] - Add a new task") print(" list - List all tasks") print(" done [task_number] - Mark a task as done") print(" delete [task_number] - Delete a task") print(" quit - Exit the program") command = input("Enter a command: ") if command.startswith("add"): task = command[4:].strip() if task: tasks.append(task) print(f"Added task: {task}") else: print("Please enter a task to add.") elif command == "list": if not tasks: print("No tasks in the list.") else: for index, task in enumerate(tasks, start=1): print(f"{index}. {task}") elif command.startswith("done"): try: task_number = int(command[5:].strip()) if 1

Mar 15, 2025 - 07:54
 0
Creating a Simple Python To-Do List Manager

Introduction

In today's fast-paced world, managing tasks efficiently is essential. A to-do list manager helps us stay organized, ensuring nothing slips through the cracks. In this article, we’ll build a simple command-line to-do list manager using Python. This program will allow users to add tasks, list them, mark them as done, delete them, and save the list for future use—all with basic Python features.

Why a To-Do List Manager?

A to-do list manager is invaluable for:

  • Organizing daily tasks.
  • Prioritizing what needs to be done.
  • Tracking completed tasks.
  • Ensuring nothing is forgotten.

Our program will be a basic version, easy to expand with additional features, making it ideal for beginners and practical for daily use.

Design and Planning

Our to-do list manager will run in the command line, with users interacting via simple commands. The supported commands are:

  • add [task]: Add a new task.
  • list: Display all tasks, with completed ones marked as [x].
  • done [task_number]: Mark a specific task as completed.
  • delete [task_number]: Remove a specific task.
  • quit: Exit the program and save the current list to a file.

Tasks will be stored in a list in memory, saved to a file upon exit, and loaded from the file when the program starts. We’ll use a simple text file for storage, with each task on a new line and completed tasks prefixed with [x].

Implementation

Here’s the step-by-step implementation of the code, with explanations for each part.

Step 1: Import Required Modules

import os

We need the os module to check if the file exists.

Step 2: Define the File Name for Saving Tasks

TODO_FILE = "todo.txt"

A constant TODO_FILE defines the name of the file where tasks will be stored.

Step 3: Function to Load Tasks

def load_tasks():
    tasks = []
    if os.path.exists(TODO_FILE):
        with open(TODO_FILE, "r") as file:
            for line in file:
                tasks.append(line.strip())
    return tasks

The load_tasks() function checks if the file exists. If it does, it reads each line as a task into a list and returns it. If not, it returns an empty list.

Step 4: Function to Save Tasks

def save_tasks(tasks):
    with open(TODO_FILE, "w") as file:
        for task in tasks:
            file.write(task + "\n")

The save_tasks(tasks) function writes the task list to the file, one task per line.

Step 5: Main Function to Handle User Interaction

def main():
    tasks = load_tasks()
    while True:
        print("\nTo-Do List Manager")
        print("Commands:")
        print("  add [task] - Add a new task")
        print("  list - List all tasks")
        print("  done [task_number] - Mark a task as done")
        print("  delete [task_number] - Delete a task")
        print("  quit - Exit the program")
        command = input("Enter a command: ")
        if command.startswith("add"):
            task = command[4:].strip()
            if task:
                tasks.append(task)
                print(f"Added task: {task}")
            else:
                print("Please enter a task to add.")
        elif command == "list":
            if not tasks:
                print("No tasks in the list.")
            else:
                for index, task in enumerate(tasks, start=1):
                    print(f"{index}. {task}")
        elif command.startswith("done"):
            try:
                task_number = int(command[5:].strip())
                if 1 <= task_number <= len(tasks):
                    task = tasks[task_number - 1]
                    if not task.startswith("[x] "):
                        tasks[task_number - 1] = f"[x] {task}"
                        print(f"Marked task {task_number} as done.")
                    else:
                        print(f"Task {task_number} is already done.")
                else:
                    print("Invalid task number.")
            except ValueError:
                print("Invalid command. Please use 'done [task_number]'.")
        elif command.startswith("delete"):
            try:
                task_number = int(command[7:].strip())
                if 1 <= task_number <= len(tasks):
                    deleted_task = tasks.pop(task_number - 1)
                    print(f"Deleted task: {deleted_task}")
                else:
                    print("Invalid task number.")
            except ValueError:
                print("Invalid command. Please use 'delete [task_number]'.")
        elif command == "quit":
            save_tasks(tasks)
            print("Goodbye!")
            break
        else:
            print("Invalid command. Please try again.")

The main() function is the core of the program. It runs a loop that prompts the user for commands and processes them. It supports adding tasks, listing them, marking them as done, deleting them, and quitting, with appropriate input validation and error handling.

Step 6: Run the Main Function

if __name__ == "__main__":
    main()

This ensures the main() function runs when the script is executed.

Explanation

  • load_tasks(): Reads tasks from todo.txt into a list.
  • save_tasks(tasks): Writes the task list to todo.txt.
  • main(): The main loop processes user commands: - add [task]: Adds a new task to the list. - list: Displays all tasks with their indices. - done [task_number]: Marks a task as done by prefixing it with [x], checking if it’s already done to avoid duplication. - delete [task_number]: Removes a task from the list. - quit: Saves the list and exits. This simple program provides a basic yet functional task management framework, easy to use and understand, perfect for everyday needs.

Testing

Here’s how to test the program:

  1. Run the program.
  2. Enter add Buy milk to add a task.
  3. Enter add Walk the dog to add another task.
  4. Enter list to see both tasks.
  5. Enter done 1 to mark the first task as done.
  6. Enter list again to see the first task marked as completed.
  7. Enter delete 2 to remove the second task.
  8. Enter list again to see only the completed task remains.
  9. Enter quit to save and exit.

Conclusion

We’ve built a simple yet effective Python to-do list manager. This program helps organize daily tasks and track their completion. Future enhancements could include adding task priorities, due dates, or even a graphical user interface.

Full Code

Here’s the complete code:

import os

TODO_FILE = "todo.txt"

def load_tasks():
    tasks = []
    if os.path.exists(TODO_FILE):
        with open(TODO_FILE, "r") as file:
            for line in file:
                tasks.append(line.strip())
    return tasks

def save_tasks(tasks):
    with open(TODO_FILE, "w") as file:
        for task in tasks:
            file.write(task + "\n")

def main():
    tasks = load_tasks()
    while True:
        print("\nTo-Do List Manager")
        print("Commands:")
        print("  add [task] - Add a new task")
        print("  list - List all tasks")
        print("  done [task_number] - Mark a task as done")
        print("  delete [task_number] - Delete a task")
        print("  quit - Exit the program")
        command = input("Enter a command: ")
        if command.startswith("add"):
            task = command[4:].strip()
            if task:
                tasks.append(task)
                print(f"Added task: {task}")
            else:
                print("Please enter a task to add.")
        elif command == "list":
            if not tasks:
                print("No tasks in the list.")
            else:
                for index, task in enumerate(tasks, start=1):
                    print(f"{index}. {task}")
        elif command.startswith("done"):
            try:
                task_number = int(command[5:].strip())
                if 1 <= task_number <= len(tasks):
                    task = tasks[task_number - 1]
                    if not task.startswith("[x] "):
                        tasks[task_number - 1] = f"[x] {task}"
                        print(f"Marked task {task_number} as done.")
                    else:
                        print(f"Task {task_number} is already done.")
                else:
                    print("Invalid task number.")
            except ValueError:
                print("Invalid command. Please use 'done [task_number]'.")
        elif command.startswith("delete"):
            try:
                task_number = int(command[7:].strip())
                if 1 <= task_number <= len(tasks):
                    deleted_task = tasks.pop(task_number - 1)
                    print(f"Deleted task: {deleted_task}")
                else:
                    print("Invalid task number.")
            except ValueError:
                print("Invalid command. Please use 'delete [task_number]'.")
        elif command == "quit":
            save_tasks(tasks)
            print("Goodbye!")
            break
        else:
            print("Invalid command. Please try again.")

if __name__ == "__main__":
    main()