Solution: Score Logger
Explore how to create a Python program that accepts user input to save player names and scores to a file, then reads and displays the saved scores. This lesson helps you understand file operations, including appending and reading data, enabling you to build programs with memory and data persistence.
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)