应该阅读几行内容,包括姓名和姓氏,并将每个学生的分数相加并打印为字典: (约翰·史密斯5 安娜·波林4.5 约翰·史密斯2 安娜·波林11)。
我不明白为什么当文件为空时,子类的“ raise FileEmpty()”除外的FileEmpty没有被引发。它什么也不返回。
import os
from os import strerror
class StudentsDataException(Exception):
pass
class BadLine(StudentsDataException):
def __init__(self):
Exception.__init__(self)
print("Bad line of data in file, terminating ...")
exit()
class FileEmpty(StudentsDataException):
def __init__(self):
Exception.__init__(self)
print("Empty file offered, terminating ...")
exit()
dict = {}
try:
fname = input("Source file name?: ")
src = open(fname, 'rt')
line = src.readline()
while len(line) != 0:
lst = line.split()
if(len(lst) < 3):
raise BadLine()
key = (lst[0], lst[1])
if key in dict:
dict[key] += float(lst[2])
else:
dict[key] = float(lst[2])
line = src.readline()
src.close()
for k, v in dict.items():
print(k, "-->", v)
except BaseException as e:
if(os.path.getsize(fname) == 0):
raise FileEmpty()
if(e == IOError):
print("I/O error occurred: ", strerror(e.errno))
if(e == ValueError):
print("Value error")
else:
print("Other error", strerror(e.errno))