Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading