Solution: Score Logger
Explore how to create a Python score logger that records player names and scores to a file and then retrieves all saved scores for display. This lesson teaches file handling with append and read modes, helping you build reusable programs with persistent memory.
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)