Search code examples
pythonfilefor-looptry-catch

How to print file content in terminal


So I am trying to make a simple program that takes names users entered put them into a file and then print the file in the terminal when EOFerror is called. It makes the file and it shows the names in it but does not print them in the terminal. Need help seeing where I went wrong

file1 = open("names.txt",'a+')

try:
    while True:
        name = input("Whats your name: ") 
        file1.write(name)
        file1.write('\n')
except EOFError:
    lines = file1.readlines()
    for line in lines:
        print('hello', line)
file1.close() 

Outputs:

Whats your name: James
Whats your name: Sally
Whats your name: ^Z

Solution

  • You need to flush your writes and seek back to the beginning to read what you wrote. If you don't seek, you start reading from where the last write ended, and there's nothing there to read.

    with open("names.txt",'a+') as file1:
        try:
            while True:
                name = input("Whats your name: ") 
                file1.write(name)
                file1.write('\n')
        except EOFError:
            file1.flush()
            file1.seek(0)
            lines = file1.readlines()
            for line in lines:
                print('hello', line)