pythonoutput

Not getting the output I want since I changed from match-case to if-else


I'm currently working on a task management list in Python and I made a small change to optimize my code. I switched from match-case to if-else, and since then there's been a problem with the output.

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

    if 'add' in user_choice or 'new' in user_choice:
        task = user_choice[4:]

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

        tasks.append(task)

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


    elif 'show' in user_choice:

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

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

In this block, every time I add a task, it gets added right next to the existing task instead of being added to a new one: enter image description here

I want the code to add tasks on separate lines instead of joining them in a single line.


Solution

  • The problem likely occurred when you added user_choice = user_choice.strip(), which removes the newline \n character at the end of your input. The method writelines() will not add a newline after each element, but expects the list to already contain strings that are terminated by \n.

    To fix this, make sure all tasks are always written with an additional \n. As those you read via readlines() already have it, you have to remove prior to re-writing the file:

    with open ('tasks.txt','w') as file:
        for task in tasks:
            task = task.strip('\n')
            file.write(task + '\n')
    

    As pointed out in the comments, you might want to look at mode 'a' when appending to an existing file.

    Also, you should check for existence of the tasks.txt file prior to reading it:

    try:
        with open ('tasks.txt','r') as file:
            tasks=file.readlines()
    except FileNotFoundError:
        tasks = []