英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论