从txt读取分数并显示最高分数和记录



从Python开始第6章练习:

  1. 高分 假定计算机磁盘上存在一个名为 scores.txt 的文件。它包含一系列记录,每个记录有两个字段 - 名称,后跟分数(1 到 100 之间的整数(。编写一个程序,显示得分最高的记录的名称和分数,以及文件中的记录数。(提示:使用变量和"if"语句来跟踪在通读记录时找到的最高分数,并使用变量来记录记录数。
Data in grades.txt
Jennifer 89
Pearson 90
Nancy 95
Gina 100
Harvey 98
Mike 99
Ross 15
Test 90

file=open('grades.txt','r')
my_list=[]
num_of_records=0
highest_score=1
highest_score_name=''
for line in file:
name,score=line.strip().split()
if int(score)>highest_score:
highest_score=int(score)
highest_score_name=name
num_of_records=num_of_records+1

print('the name and score of the record with highest score:')
print('Name:',highest_score_name)
print('Score:',highest_score)
print('nNumber of records:',num_of_records)
file.close()

在这里使用python的总入门,并试图通过这本书 但是遇到这个问题的错误。

错误:

line 9, in <module> name,score=line.strip().split() 
ValueError: not enough values to unpack (expected 2, got 0)

任何指南都值得赞赏。

好的,知道了,实际上正在发生的事情是您的数据在文件末尾有一个换行符,当您尝试拆分时会导致错误。这是正确的代码:

file = open('grades.txt', 'r')
num_of_records = 0
highest_score = 1
highest_score_name = ''
for line in file:
line = line.strip()
# Check whether the line is empty
if line == '':
continue
name, score = line.split()
if int(score) > highest_score:
highest_score = int(score)
highest_score_name = name
num_of_records = num_of_records+1

print('the name and score of the record with highest score:')
print('Name:', highest_score_name)
print('Score:', highest_score)
print('nNumber of records:', num_of_records)
file.close()

希望对您有所帮助:(

根据您的评论,您遇到了此错误:

line 9, in <module> name,score=line.strip().split() ValueError: not enough values to unpack (expected 2, got 0)

这表示文件的一行存在问题。我假设您的文件中有一个空行。您可以在解压缩值之前检查这一点,也可以使用try/except进行错误处理。由于您还很早,我认为检查该行是否包含任何内容与学习进度相当:

if line.strip():
name,score=line.split()

这样,只有在删除空格后变量不为空时,您才会解压缩行。