如何解决Python程序覆盖现有文本文件及排行榜读取报错问题
双人骰子游戏排行榜问题解决方案
问题原因
- 文件打开模式错误:开头用
'w'模式打开文件会直接清空原有历史数据,且每次运行都重复写入表头,导致表头混入得分数据参与排序。 - 排序逻辑错误:直接对整行字符串做排序,未提取分数字段按数值排序,同时表头也参与了排序,导致输出结果不符合预期。
- 索引越界原因:代码强制循环5次读取
sortedData的前5个元素,当文件内有效数据行数不足5时,就会访问不存在的列表下标,抛出IndexError。
修正后代码
import os # 仅当排行榜文件不存在时写入表头,避免清空历史数据 if not os.path.exists("Leaderboard.txt"): with open("Leaderboard.txt", 'w', encoding='utf-8') as file: file.write("Name " + "Score" + "\n") # 追加写入当前对局的两名玩家得分 with open("Leaderboard.txt", 'a', encoding='utf-8') as file: file.write(f"{player1}:{score1}\n") file.write(f"{player2}:{score2}\n") # 读取排行榜数据 score_list = [] with open("Leaderboard.txt", 'r', encoding='utf-8') as file: # 跳过表头行 header = file.readline() for line in file: line = line.strip() if not line: continue # 拆分用户名和分数 name, score = line.split(':') score_list.append((int(score), name)) # 按分数倒序排序 sorted_score = sorted(score_list, reverse=True) # 打印前5名排行榜 print(' ') print("==============================") print(" Top 5 Winning Scores") print(' ') # 只取前5条,且仅遍历实际存在的条目,避免索引越界 for idx, (score, name) in enumerate(sorted_score[:5], 1): print(f"{idx}\t{name}:{score}")
代码说明
- 引入文件存在性判断逻辑,仅首次创建文件时写入表头,从根源避免历史数据被清空、表头重复写入的问题。
- 读取数据时跳过表头,拆分每行的用户名和分数字段,将分数转为整型后排序,保证排序结果完全匹配得分高低逻辑。
- 输出时自动截断取排序后的前5条数据,仅遍历实际存在的条目,彻底解决索引越界错误。
- 使用
with open语法自动管理文件句柄,无需手动调用close(),避免文件资源泄漏。
内容的提问来源于stack exchange,提问作者Vedant
相关产品推荐
相关产品推荐

