我已经创建了一个小的顶级王牌游戏,并有一个csv文件,从以前的游戏中存储所有的分数。我如何让它打印最高分?
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))
创建一个变量来记住最高分,并将其初始化为0。
逐行读取csv文件。如果你看到一个分数高于之前的最高分,记住它作为新的最高分。
在循环结束时,打印最高分。
# 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)