AttributeError:'list'对象没有属性'readline'?

时间:2020-12-25 18:17:35
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)

Prints before main body are just for debugging, problem is while loop is not stopping even when line == '', EOF

主体之前的打印只是用于调试,问题是while循环没有停止,即使行=='',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

The file grade.txt ends after an \n "99" i.e. it is like 99\n

文件grade.txt在\ n“99”之后结束,即它就像99 \ n

This is an question from Python tut on coursera

这是Python tut on coursera的一个问题

Any help will be grateful

任何帮助将不胜感激

1 个解决方案

#1


If you only want the second column in your file as floats:

如果您只希望文件中的第二列为浮点数:

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

This assumes you want throw away the first two lines in the file. You split each line at whitespace and convert all numbers in the second column to floats.

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

Now:

grades = read_grade(gradefile)
range_grade(grades)

returns:

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

#1


If you only want the second column in your file as floats:

如果您只希望文件中的第二列为浮点数:

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

This assumes you want throw away the first two lines in the file. You split each line at whitespace and convert all numbers in the second column to floats.

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

Now:

grades = read_grade(gradefile)
range_grade(grades)

returns:

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