I've created a little top trumps game and have a csv file that stores all the scores from previous games. How do I get it to print the highest score?
field_names = ['player_name','score']
data = [{"player_name": player_name, 'score': score}]
with open("score.csv", "a") as csv_file:
spreadsheet = csv.DictWriter(csv_file, fieldnames=field_names)
spreadsheet.writerows(data)
with open('score.csv', 'r') as csv_file:
spreadsheet = csv.DictReader(csv_file)
for row in spreadsheet:
print(dict(row))
CodePudding user response:
Create a variable to remember the highest score, and initialize it to zero.
Read the csv file row by row. If you see a score that is higher than the previous highest score, remember it as the new highest score.
At the end of the loop, print the highest score.
# initialize to a placeholder value
highest_score = 0
# read the csv file
with open('score.csv', 'r') as csv_file:
spreadsheet = csv.DictReader(csv_file)
for row in spreadsheet:
# convert the score column to an integer
intscore = int(row['score'])
# if this score is the highest so far, remember it
if intscore > highest_score:
highest_score = intscore
print(highest_score)