pythonif-statementmatch

Python Todo List not Adding New Todo in New Row, Rather It Is Appending on the Same Line as Previous Todo


I am a beginner in Python. This Todo List is not Adding New Todo in New Row, Rather It Is Appending on the Same Line as Previous Todo. When it was add as 'match case' it worked properly but since changing it to 'if add' it appends on the same row as in: "1. clean car go get groceries" instead of "1. clean car 2. go get groceries".

from unittest import case
from urllib.response import addbase

while True:
    user_action = input("Type add, show, edit, complete or exit : ")
    user_action = user_action.strip()

    if 'add' in user_action or 'new' in user_action or 'more' in user_action:
        todo = user_action[4:]

        with open('todos.txt', 'r') as file:
            todos = file.readlines()

        todos.append(todo)

        with open('todos.txt', 'w') as file:
            file.writelines(todos)

    elif 'show' in user_action:
        with open('todos.txt', 'r') as file:
            todos = file.readlines()


        for index, item in enumerate(todos):
            item = item.strip('\n')
            row = f"{index + 1} - {item}"
            print(row)

    elif 'edit' in user_action:
        number = int(user_action[5:])
        print(number)
        number = number - 1

        with open('todos.txt', 'r') as file:
            todos = file.readlines()
            print('Here are existing todos', todos)

            new_todo = input("Enter a new todo: ")
            todos[number] = new_todo + '\n'

            with open('todos.txt', 'w') as file:
                file.writelines(todos)

    elif 'complete' in user_action:
            number = int(user_action[9:])

            with open('todos.txt', 'r') as file:
                todos = file.readlines()
                index = number - 1
                todo_to_remove = todos[index].strip('\n')
                todos.pop(index)

            with open('todos.txt', 'w') as file:
                file.writelines(todos)

            message = f"Todo {todo_to_remove} was removed from the list."
            print(message)

    elif 'exit' in user_action:
        break

    else:
        print("Invalid input")

print("bye")





I expected the code to output the list in .txt file and console as enumerated rows but instead it is now outputting text in the console and .txt file all new todos in one row smooshed togethr with previous todos.


Solution

  • Make sure you’re adding a newline (\n) at the end of each todo item when you append it to the list. Here’s the relevant part of your code corrected:

    if 'add' in user_action or 'new' in user_action or 'more' in user_action:
        todo = user_action[4:]
        with open('todos.txt', 'r') as file:
            todos = file.readlines()
    
        todos.append(todo + "\n")  # Add the new todo with a newline at the end
    
        with open('todos.txt', 'w') as file:
            file.writelines(todos)