[英]Python 3: My code is suppose to print one name and one score from this file but its prints the name twice and the score twice. Why?
This is the assignment:这是作业:
This is my code so far:到目前为止,这是我的代码:
def main():
Continue = 'yes'
golf_file = open('golf.txt', 'a')
while Continue == 'yes':
player_name = input("Input the player's name: ")
player_score = input("Input the player's score: ")
golf_file.write(player_name + "\n")
golf_file.write(str(player_score) + "\n")
Continue = input("Would you like to continue? [yes]: ")
display_file = input("Would you like to display the records from the golf.txt? [yes]: ")
golf_file.close()
if(display_file == 'yes'):
displayfile()
def displayfile():
golf_file = open('golf.txt', 'r')
for line in golf_file:
print("The score of this person is: ",line)
print("The name of this person is: ",line)
golf_file.close()
main()
When the names/scores print it looks like this:当名字/分数打印时,它看起来像这样:
You are reading one line (that contains the name), and printing it as the name and the score.您正在阅读一行(包含姓名),并将其打印为姓名和乐谱。 Then you read the next line containing a score) and print it as the name and the score again.
然后你阅读包含分数的下一行)并再次将其打印为名称和分数。
You want to alternate treating a line as a name or a score, something like您想交替将一行视为名称或分数,例如
def displayfile():
with open('golf.txt', 'r') as golf_file:
for name in golf_file:
print("The name of this person is: ", name)
score = next(golf_file)
print("The score of this person is: ", score)
Because golf_file
is its own iterator, calling next
in the body of the loop advances the file pointer by one line, so that the loop always resumes by reading a name line.因为
golf_file
是它自己的迭代器,所以在循环体中调用next
会使文件指针前进一行,因此循环总是通过读取名称行来恢复。
Something a little more symmetric might be更对称的东西可能是
def displayfile():
with open('golf.txt', 'r') as golf_file:
while True:
try:
name = next(golf_file)
score = next(golf_file)
except StopIteration:
break
print("The name of this person is: ", name)
print("The score of this person is: ", score)
Even simpler, though, would be to write each name and score on a single line.不过,更简单的方法是将每个名字和分数写在一行上。
def main():
with open('golf.txt', 'a') as golf_file:
while True:
player_name = input("Input the player's name: ")
player_score = input("Input the player's score: ")
golf_file.write(f"{player_name}\t{player_score}\n")
continue = input("Would you like to continue? [yes]: ")
if continue != 'yes':
break
display_file = input("Would you like to display the records from the golf.txt? [yes]: ")
if display_file == 'yes':
displayfile()
def displayfile():
with open('golf.txt', 'r') as golf_file:
for line in golf_file:
name, score = line.strip().split('\t')
print("The score of this person is: ", name)
print("The name of this person is: ", score)
main()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.