AttributeError: 'list' object has no attribute 'readline'?

AttributeError: 'list' object has no attribute 'readline'?

def read_grade(gradefile):

    '''
    (file,'r') --->  list of floats

    In this case it will return grade from file,   
    this fution is meant to use with given grade file'''

    line = gradefile.readline()
    print(line) 
    while line != '\n':
       line = gradefile.readline()
       print(line) 

   grades = []

   line = gradefile.readline()
   print(line)

    while line != '':
       grade = line[line.rfind(' ') + 1:]
       grades.append(float(grade))
       line = gradefile.readline()
       print(line)

    return grades

def range_grade(grades):        
    '''
    (list of int) ---> list of int

    Return a list where each index indicates how many grades were in these ranges
   '''
   grade_range = [0] *11

   for grade in grades:
      which_range = int(grade // 10)
      grade_range[which_range] = grade_range[which_range] + 1

   return grade_range


 #Main body starts


 file_path = 'C:/Users/user_name/Desktop/python/grade.txt'
 file = open(file_path,'r')

 hista_file_path ='C:/Users/user_name/Desktop/python/hista.txt'
 hista_file = open(hista_file_path,'w')


#read grades

grades = read_grade(file)

#count grade per range

range_counts = read_grade(grades)

print(range_counts)

主体之前的打印只是为了调试,问题是 while 循环没有停止,即使当 line == '', EOF

grade.txt

*Grade File for python learning created by Mukul Jain on 11 May 2015

0052 77.5
0072 66
0133 100
0123 89
0402 51
0032 72
0144 22
0082 26
0024 79
0145 12
0524 60
0169 99

文件 grade.txt 在\n "99" 后结束,即类似于 99\n

这是来自 Python tut on coursera 的问题

如有帮助将不胜感激

如果您只想将文件中的第二列作为浮点数:

def read_grade(gradefile):
    next(gradefile)
    next(gradefile)
    return [float(line.split()[1]) for line in gradefile]

这假定您要丢弃文件中的前两行。 您在空格处拆分每一行并将第二列中的所有数字转换为浮点数。

现在:

grades = read_grade(gradefile)
range_grade(grades)

returns:

[0, 1, 2, 0, 0, 1, 2, 3, 1, 1, 1]