This is the assignment:
- The first program will read each player’s name and golf score as keyboard input, then save these as records in a file named golf.txt. (Each record will have a field for the player’s name and a field for the player’s score.)
- The second program reads the records from the golf.txt file and displays them.
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:
>Solution :
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.
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()
