Linked Questions

Popular Questions

Output not being printed on new lines

Asked by At

Output not being printed in a different line in the stored file in Python.

What am I doing wrong and why is the output all in the same line? I know I have to use "\n" somewhere but not sure where exactly.

while True:
    # Get user input and remove leading/trailing spaces
    user_action = input("Type add, show, edit, complete, or exit: ")
    user_action = user_action.strip()

    if 'add' in user_action:
        # Extract the todo item from user's input
        todo = user_action[4:] + '\n'

        # Read the existing todos from the file
        with open('todos.txt', 'r') as file:
            todos = file.readlines()

        # Append the new todo item to the list
        todos.append(todo)

        # Write the updated todos list back to the file
        with open('todos.txt', 'w') as file:
            file.writelines(todos)

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

        # Display the todos with their corresponding index numbers
        for index, item in enumerate(todos):
            # Remove the newline character from each item
            item = item.strip("\n")

            # Format the todo item with its index number
            num = f"{index + 1}-{item}\n"

            # Print the formatted todo item
            print(num)

Being an absolute beginner I'm not able to formulate where I am supposed to use "\n" so that the output is written in the next line.

Related Questions