如何在终端打印文件内容

问题描述 投票:0回答:1

所以我试图制作一个简单的程序,将用户输入的名称放入文件中,然后在调用 EOFerror 时在终端中打印该文件。它创建文件并显示其中的名称,但不会在终端中打印它们。需要帮助看看我哪里出错了

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() 

输出:

Whats your name: James
Whats your name: Sally
Whats your name: ^Z
python file for-loop io try-catch
1个回答
0
投票

您需要刷新您的写入内容并返回到开头来阅读您所写的内容。

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)
© www.soinside.com 2019 - 2024. All rights reserved.