179. Python Program to Save and Load a Score List
Hardwith
Overview
Put the whole chapter together: write a file, read it back, and turn its text into real data.
Problem Statement
Read a whole number n, then n lines, each a name and a score separated by a comma, like Sunny,80. There may be spaces around the name or the score: strip them.
- Save the scores in a file called
scores.txt, onename,scoreline each, usingwith open(...). - Load them back from
scores.txt: split each line at the comma and turn the score into a number. - Using the loaded scores, print each player as
name: score, then the best player asBest: name (score), then the average with two decimals asAverage: 82.33.
If two players share the best score, the one who came first is the best. n is always at least 1.
Write a function to save and a function to load. For example: save_scores(filename, records) and load_scores(filename), where each record is a (name, score) tuple.
Your program runs in the browser, so the file lives only in this tab's memory. Create it with "w" before you read it.
Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Input
The number of players, then one name,score per line. Example:
3
Sunny,80
Rocky,95
Lucky,72
Output
The output for that example:
Sunny: 80
Rocky: 95
Lucky: 72
Best: Rocky (95)
Average: 82.33
The tests try 4 different inputs, including one player and a tie for the best score.