# file operation can be replaced with one line codeprint(sorted(set([sanitize(each_t)foreach_tinget_date("james.txt")]))[0:3])
Bundle the code and data in a dictionary
12345678910111213141516
defget_data(filename):try:withopen(filename)asfile:data=file.readline()temp=data.strip().split(',')# return a dictionaryreturn({'Name':temp.pop(0),'DOB':temp.pop(0),'Times':str(sorted(set([sanitize(each_t)foreach_tintemp]))[0:3])})exceptIOErrorasioerr:print('File error: '+str(ioerr))return(None)sarah=get_data('sarah2.txt')print(sarah['Name']+"'s fastest times are: "+sarah['Times'])
Amend the code and data in a class that inherit from BIF list
12345678910111213141516171819
classAthlete(list):def__init__(self,a_name,a_dob=None,a_times=[]):list.__init__([])self.name=a_nameself.dob=a_dobself.extend(a_times)deftop3(self):return(str(sorted(set([sanitize(each_t)foreach_tinself]))[0:3]))defget_data(filename):try:...return(Athlete(temp.pop(0),temp.pop(0),temp))exceptIOErrorasioerr:...sarah=get_data('sarah2.txt')print(sarah.name+"'s fastest times are: "+sarah.top3())
Model the data
Put class AthleteList in a module file
12345678910111213141516171819202122232425262728
importpickle# class AthleteList is saved in athletelist.py, import AthleteList using this line of code# use dir() command to confirm that the import has been successfulfromathletelistimportAthleteListdefget_data(filename):...defput_to_store(file_list):all_athletes={}foreach_fileinfile_list:ath=get_data(each_file)all_athletes[ath.name]=athtry:withopen('athletes.pickle','wb')asathf:pickle.dump(all_athletes,athf)exceptIOErrorasioerr:print('File error (put_and_store): '+str(ioerr))return(all_athletes)defget_from_store():all_athletes={}try:withopen('athletes.pickle','rb')asathf:all_athletes=pickle.load(athf)exceptIOErrorasioerr:print('File error (get_from_store): '+str(ioerr))return(all_athletes)