Solution: Score Logger
Discover how to build a Python score logger that collects player names and scores, appends them to a file, and reads all saved entries. This lesson teaches file operations using open in append and read modes, handling user input, and organizing code with functions and dictionaries for reusable programming.
We'll cover the following...
This program lets a player enter their name and score, saves it to a file, and then reads the file to show all saved scores.
input()asks the user to type their name and score.The first
with open("scores.txt", "a") as file:opens the file named scores.txt in append mode ("a"), which means new entries are added to the end of the file without erasing old ones.file.write()saves the player’s name and score in the formatName:Score, followed by a new line (\n).The second
with open("scores.txt", "r") as file:opens the same file in read mode ("r").file.read()reads the entire content of the file.print(content)displays all the saved scores on the screen.
name = input("Player name: ")
score = input("Score: ")
with open("scores.txt", "a") as file:
file.write(name + ":" + score + "\n")
with open("scores.txt", "r") as file:
content = file.read()
print(content)