Golf Scores
The Springfork Amateur Golf Club has a tournament every weekend. The club president has asked you to write two programs:
1. A program that will read each player’s name and golf score as keyboard input, and 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.)
2. A program that reads the records from the golf.txt file and displays them.
Golf Scores:
1) First Program code:
def savePlayerRecords():
try:
#Prompt and read the each player’s name
#and golf score from the user
numPlayers = int(input("Enter the number of players: "))
#save these as records in a file named golf.txt
with open("golf.txt", "w") as file:
for _ in range(numPlayers):
playerName = input("Enter player name: ")
score = input("Enter player score: ")
file.write(playerName + "," + score + "\n")
print("Player records saved successfully in file 'golf.txt'.")
except Exception as e:
print("An error occurred:", str(e))
savePlayerRecords()
Executed Output:
Enter the number of players: 2
Enter player name: Josh
Enter player score: 80
Enter player name: Don
Enter player score: 90
Player records saved successfully in file 'golf.txt'.
Output data in 'golf.txt' file:
Josh,80
Don,90
2) Second Program code:
def displayPlayerRecords():
try:
#Reads the records from the golf.txt file
#and displays them.
with open("golf.txt", "r") as file:
for line in file:
playerData = line.strip().split(",")
playerName = playerData[0]
score = playerData[1]
print("Player Name:", playerName)
print("Score:", score)
print("-----------------------")
except FileNotFoundError:
print("Player records file not found.")
except Exception as e:
print("An error occurred:", str(e))
displayPlayerRecords()
Data in 'golf.txt' file:
Josh,80
Don,90
Executed Output:
Player Name: Josh
Score: 80
------------------
Player Name: Don
Score: 90
------------------