Output not being printed on new lines

59 views 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.

1

There are 1 answers

0
Narges M. On

You are correctly appending the newline character ('\n') to each todo item when you add it to the todos list. However, the issue lies in how you are writing the todos list back to the file.

When you use the writelines() method to write the list to the file, it writes each element of the list as-is, without adding any additional characters. That's why all the items are written in the same line.

To resolve this, you can modify your code. Here is just one example of how you may do so:

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

In this code, each todo item will be written on a separate line in the file due to the '\n' character used as the separator in join().