How to Create a .txt Score File in Python

The script below updates the score for each user.  It first inputs the user’s name.  If the user doesn’t already exist in the scores.json file, then it adds the user to the scores.json file and the player’s score.  If the user already exists in this file, then it updates the player’s score.

Script 1. Create Score

					import json

# Load the scores from the scorefile
    with open('scores.json', 'r') as f:
        scores = json.load(f)
except (FileNotFoundError, json.decoder.JSONDecodeError):
    scores = {}

# Get the user's name and score
name = input("Enter your name: ")
score = 2

# Update the scores dictionary
if name in scores:
    scores[name] += score
    scores[name] = score

# Save the scores to the scorefile
with open('scores.json', 'w') as f:
    json.dump(scores, f)


Scores.json File: Save a scores.json file in the same directory as your Create Score file.

					{"Brandon": 14, "Mary": 9}
Scroll to Top