如何在终端中打印文件内容

huangapple go评论78阅读模式
英文:

How to print file content in terminal

问题

I've translated the code portion for you:

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

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

If you have any more specific questions or need assistance with this code, please let me know.

英文:

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

答案1

得分: 1

你需要刷新你的写入并将读取位置回到开头以读取你所写的内容。如果不回到开头,你会从上次写入结束的位置开始读取,而那里没有可读的内容。

with open("names.txt", 'a+') as file1:
    try:
        while True:
            name = input("你的名字是什么: ")
            file1.write(name)
            file1.write('\n')
    except EOFError:
        file1.flush()
        file1.seek(0)
        lines = file1.readlines()
        for line in lines:
            print('你好', line)
英文:

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)

huangapple
  • 本文由 发表于 2023年8月5日 06:38:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76839440.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定