python 如何在外部csv文件上打印最高分

m1m5dgzv  于 2022-11-28  发布在  Python
关注(0)|答案(1)|浏览(126)

我已经创建了一个小的顶级王牌游戏,并有一个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))
p5fdfcr1

p5fdfcr11#

创建一个变量来记住最高分,并将其初始化为零。
逐行阅读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)

相关问题