Python高尔夫记录查询searchRecs函数实现问题求助
问题修复方案
问题根因
- 你采用的存储规则为姓名占1行、对应分数紧挨着占下1行,匹配到姓名所在行后直接读取下一行即可拿到对应分数
- 此前重复打开文件、调用
read()读完内容后未重置文件指针,是触发报错和仅能输出姓名的核心原因
修复后完整代码
def main(): move_on = 'y' golfScoreFile = open('golfRecords.txt', 'a') while move_on.lower() == 'y': pName = input("Enter the player's name: ") pScore = int(input("Enter the player's score: ")) golfScoreFile.write(pName + "\n") golfScoreFile.write(str(pScore) + "\n") move_on = input("Would you like to continue? [y]: ") displayRecords = input("Would you like to display all the records from golfRecords.txt? [y]: ") golfScoreFile.close() if displayRecords.lower() == 'y': displayRecs() else: searchRecs() def displayRecs(): golfScoreFile = open('golfRecords.txt', 'r') lineCount = 1 for line in golfScoreFile: golfRecLine = lineCount % 2 if golfRecLine == 0: print("The score of this person is: ", line.strip()) if golfRecLine == 1: print("The name of this person is: ", line.strip()) lineCount = lineCount + 1 golfScoreFile.close() def searchRecs(): search = input("Enter player name: ").strip() found = False # 用with语法自动管理文件句柄,不用手动调用close() with open('golfRecords.txt', 'r') as file: for line in file: # 去掉换行符再匹配,避免格式误差导致匹配失败 if line.strip() == search: # 迭代器下一行就是对应分数 score = next(file).strip() print(f"球员姓名:{search},对应分数:{score}") found = True # 如果需要查找所有同名球员的记录,删除下面的break即可 break if not found: print("未查询到对应球员的分数记录") if __name__ == "__main__": main()
额外优化点
- 用
lower()统一识别大小写的Y输入,简化判断逻辑 - 所有输出内容调用
strip()去掉多余换行符,打印格式更整洁 - 增加未找到记录的提示,逻辑更完整
内容的提问来源于stack exchange,提问作者mas284
相关产品推荐
相关产品推荐

