February 8, 2024

To-Do List App in Python

Posted on February 8, 2024  •  4 minutes  • 648 words

Creating a Todo List Command Line Application in Python

Prerequisites :

Make sure you have Python installed on your system.

In this tutorial, we will create a simple command-line Todo List application using Python. The application allows users to

  1. add tasks,
  2. list tasks,
  3. remove tasks,
  4. add labels to tasks, and
  5. clear all tasks.

The tasks are stored in a text file for persistence.

It supports the following commands:

  1. add <task-name> [label-1] ...[label-n] : Add a new task with optional labels.

  2. ls: Show the list of tasks.

  3. rm <task-number>: Delete an existing task.

  4. add-labels <task-number> <label-1> ...[label-n]: Add additional labels to an existing task.

  5. clear: Delete all tasks.

Let’s go through the key components of the application:

Let’s go through each function in the application:

1. Adding a Task (add_task)

  1. Adds a new task to the Todo List.
  2. Takes a list of arguments (args) representing the task name and optional labels.
  3. Appends the task to the TODO_FILE and then calls list_tasks() to display the updated list.

def add_task(args):
    if len(args) < 1:
        print("Error: Task name cannot be empty.")
        return
    task_name = " ".join(args)
    if not task_name:
        print("Error: Task name cannot be empty.")
        return

    with open(TODO_FILE, "a") as file:
        file.write(task_name + "\n")
    
    print(f"Task added: {task_name}")
    list_tasks()

2. Listing Tasks (list_tasks)

  1. Loads tasks from the TODO_FILE into the todo_list.
  2. Displays the current list of tasks along with their indices.

def list_tasks():
    load_tasks()
    if len(todo_list) > 0:
        print("TODO List:")
    else:
        print("No tasks found.")
        return
    for i, task in enumerate(todo_list, start=1):
        print(f"{i}. {task.strip()}")

3. Removing a Task (remove_task)

  1. Removes an existing task from the Todo List.
  2. Takes a list of arguments (args) with the task number to be removed.
  3. Removes the specified task from todo_list and updates the TODO_FILE.

def remove_task(args):
    task_number = args[0]
    if is_integer(task_number) and int(task_number) > 0 and int(task_number) <= len(todo_list):
        task_index = int(task_number)-1
        print("Deleting ", todo_list[task_index])
        todo_list.remove(todo_list[task_index])
        writeToFile()

4. Adding Labels to a Task (add_labels)

  1. Adds additional labels to an existing task.
  2. Takes a list of arguments (args) with the task number and labels to be added.
  3. Modifies the specified task in todo_list by appending the new labels and updates the TODO_FILE.

def add_labels(args):
    if len(args) < 2:
        print("Give Valid task number and labels")
        print("todo add-labels <task-number> <label-1> ...[label-n]")
        return
    task_number = args[0]
    labels = args[1:]
    if is_integer(task_number) and int(task_number) > 0 and int(task_number) <= len(todo_list):
        task_index = int(task_number)-1
        print("Updating ", todo_list[task_index])
        current_task_and_labels = str(todo_list[task_index]).split(" ")
        for label in labels:
            current_task_and_labels.append(label)
        todo_list[task_index] = " ".join(current_task_and_labels)
        writeToFile()
    else:
        print("Give Valid task number")
        print("todo add-labels <task-number> <label-1> ...[label-n]")
    list_tasks()

5. Clearing All Tasks (clear_all)

  1. Clears all tasks from the todo_list and updates the TODO_FILE.

def clear_all():
    todo_list.clear()
    writeToFile()

6. Load all tasks from File (load_tasks)

  1. Clears the todo_list and loads tasks from the TODO_FILE into it.

def load_tasks():
    todo_list.clear()
    try:
        with open(TODO_FILE, "r") as file:
            tasks = file.readlines()
            if tasks:
                for i, task in enumerate(tasks, start=1):
                    todo_list.append(task.strip())
            else:
                pass
    except FileNotFoundError:
        pass

7. Write all tasks to file (writeToFile)

  1. Writes the current state of the todo_list to the TODO_FILE.

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

8. Print the help content (show_help)

  1. Displays the usage instructions and available commands for the Todo List application.

def show_help():
    print("Usage: todo <command> [arguments]")
    print("Commands:")
    print("  add <task-name> [label-1] ...[label-n] - Add a new task with labels")
    print("  ls - Show the list of tasks")
    print("  rm <task-number> - Delete the existing task")
    print("  add-labels <task-number> <label-1> ...[label-n] - add additional info to existing task")
    print("  clear - Delete all tasks")

Congratulations! You’ve created a simple Todo List application in Python. Feel free to customize and enhance the application based on your needs. You can integrate additional features, or add support for different storage mechanisms.

Example Commands

python todo.py add Buy groceries personal

python todo.py ls

python todo.py rm 1

python todo.py add-labels 1 work urgent

python todo.py clear

🔗 GitHub Repository:

Link to GitHub Repo : https://github.com/Anooppandikashala/todo_shell_app

Follow me

I work on everything coding and share developer memes