提问在注释里
class StudentsDataException(Exception):
pass
#这里的pass是pass所有exception,下面代码为何还要raise exception?
class BadLine(StudentsDataException):
def __init__(self, line_number, line_string):
super().__init__(self)
self.line_number = line_number
self.line_string = line_string
这个class的具体作用是什么,能否解释一下每条代码的作用
class FileEmpty(StudentsDataException):
def __init__(self):
super().__init__(self)
from os import strerror
data = { }
file_name = input("Enter student's data filename: ")
line_number = 1
try:
f = open(filename, "rt")
lines = f.readlines()
f.close()
if len(lines) == 0:
raise FileEmpty()
for i in range(len(lines)):
line = lines[i]
columns = line.split()
if len(columns) != 3:
raise BadLine(i + 1, line)#能否解释一下(i+1,line)是什么情况
student = columns[0] + ' ' + columns[1]
try:
points = float(columns[2])
except ValueError:
raise BadLine(i + 1, line)
try:
#print(data[student]),这里print根本没有显示任何内容,只是想看一下能print什么
data[student] += points#想知道data[student]起始是不是0
except KeyError:
data[student] = points#keyerror的话没有映射对象,这里的“data[student] = points”代表什么意思
for student in sorted(data.keys()):
print(student,'\t', data[student])
except IOError as e:
print("I/O error occurred: ", strerror(e.errno))
except BadLine as e:
print("Bad line #" + str(e.line_number) + " in source file:" + e.line_string)
except FileEmpty:
print("Source file empty")
"""
文件里的内容:
John Smith 5
Anna Boleyn 4.5
John Smith 2
Anna Boleyn 11
Andrew Cox 1.5
最后的output是
Andrew Cox 1.5
Anna Boleyn 15.5
John Smith 7.0
"""