新手开发者求助:StarWars Top Trump游戏读取CSV最高分报ValueError
StarWars Top Trump游戏最高分读取错误排查
错误原因解析
你碰到的ValueError: invalid literal for int() with base 10: 'score',是因为代码把CSV文件的表头字符串'score'当成了分数数值去转成整数,自然会报错。
核心问题点
- 文件读写逻辑混乱:游戏循环里重复用
"w"模式打开文件,每次都会清空原有内容并重新写表头,导致历史分数丢失,后续读取时容易误处理表头。 - 读取时机错误:你把
csv.DictReader的定义放在了文件关闭的with块外面,此时文件已经关闭,迭代器失效,后续遍历拿不到有效数据。 - 分数处理不严谨:没有处理CSV里的空行、无效值,也没考虑文件不存在的情况。
修复后的完整代码
import random import requests import csv def random_person(): person_number = random.randint(1, 82) url = 'https://swapi.dev/api/people/{}/'.format(person_number) response = requests.get(url) person = response.json() return { 'name': person['name'], 'height': person['height'], 'mass': person['mass'], 'birth year': person['birth_year'], } def run(): highest_score = 0 field_names = ['player_name', 'score'] # 初始化或读取历史最高分 try: with open('score.csv', 'r') as csv_file: spreadsheet = csv.DictReader(csv_file) for row in spreadsheet: # 跳过空行或无效的score字段 if not row.get('score'): continue try: intscore = int(row['score']) if intscore > highest_score: highest_score = intscore except ValueError: continue except FileNotFoundError: # 文件不存在则创建并写入表头 with open('score.csv', 'w') as csv_file: spreadsheet = csv.DictWriter(csv_file, fieldnames=field_names) spreadsheet.writeheader() print('The highest score to beat is', highest_score) game = input('Do you think you can beat it? y/n') if game == 'y': print('Good Luck🙌🏽') else: print('You got this🙌🏽') print('Hello stranger, Welcome to StarWars Top Trump!') player_name = input('What is your name?') lives_remaining = 1 score = 0 while lives_remaining > 0: my_person = random_person() print(player_name, ', you were given', my_person['name']) while True: stat_choice = input('Which stat do you want to use? ( height, mass, birth year)') # 统一小写判断,避免大小写输入错误 cleaned_choice = stat_choice.strip().lower() if cleaned_choice not in ('height', 'mass', 'birth year'): print('Not an appropriate answer. Try again.') else: stat_choice = cleaned_choice break opponent_person = random_person() print('The opponent chose', opponent_person['name']) my_stat = my_person[stat_choice] opponent_stat = opponent_person[stat_choice] # 处理数值类属性的比较(身高、质量转成数字) try: my_stat_val = float(my_stat) if '.' in my_stat else int(my_stat) opponent_stat_val = float(opponent_stat) if '.' in opponent_stat else int(opponent_stat) except ValueError: # 出生年份带BBY/ABY,直接用字符串比较 my_stat_val = my_stat opponent_stat_val = opponent_stat if my_stat_val > opponent_stat_val: print(player_name, 'You Win! 🙌🏽') score += 1 elif my_stat_val == opponent_stat_val: print('Its A Draw!') else: lives_remaining -= 1 print(player_name, 'You Lost a Life!') print(player_name, 'You have', lives_remaining, 'lives remaining!') print('Your score is', score) # 游戏结束后才追加写入分数,保留历史记录 with open("score.csv", "a", newline='') as csv_file: spreadsheet = csv.DictWriter(csv_file, fieldnames=field_names) # 检查文件是否为空,空文件先写表头 csv_file.seek(0) if not csv_file.read(1): spreadsheet.writeheader() spreadsheet.writerow({"player_name": player_name, 'score': score}) # 更新并打印最新最高分 with open('score.csv', 'r') as csv_file: spreadsheet = csv.DictReader(csv_file) for row in spreadsheet: try: intscore = int(row['score']) if intscore > highest_score: highest_score = intscore except ValueError: continue print(f"Updated highest score is: {highest_score}") run()
关键修复说明
- 文件读写优化:只在游戏结束后追加写入分数,不再每轮清空文件,保留所有历史记录;处理文件不存在的初始化场景。
- 鲁棒性提升:读取分数时跳过空行和无效值,避免转换报错;数值类属性转成数字再比较,解决字符串比较的逻辑错误(比如"180"和"90"字符串比较会出错)。
- 读取逻辑修正:所有文件读取操作都放在
with块内,确保文件处于打开状态,迭代器能正常获取数据。
内容的提问来源于stack exchange,提问作者bobby brown
相关产品推荐
相关产品推荐

