Page 260 -
P. 260

model module




                              Here is the outline for a new module called athletemodel.py, which provides the
                              functionality described on the previous page. Some of the code is already provided for you. Your
                              job was to provide the rest of the code to the put_to_store() and get_from_store()
                              functions. You were not to forget to protect any file I/O calls.

                              import pickle
                              from athletelist import AthleteList

                              def get_coach_data(filename):
                                  # Not shown here as it has not changed since the last chapter.


                              def put_to_store(files_list):
                                  all_athletes = {}
             T ake each file, turn it        for each_file in files_list:
             into an AthleteList                                                Each athlete’s name is
             object instance, and             ath = get_coach_data(each_file)   used as the “key” in the
             add the athlete’s data                                            dictionary. The “value” is
                                        all_athletes[ath.name] = ath
             to the dictionary.                                                the AthleteList object
                                    try:                                       instance.

                                        with open(‘athletes.pickle', ‘wb') as athf:
                 Save the entire
                 dictionary of                  pickle.dump(all_athletes, athf)   And don’t forget
                 AthleteLists                                                     a try/except to
                 to a pickle.        except IOError as ioerr:                      protect your file

                                        print(‘File error (put_and_store): ' + str(ioerr))  I/O code.
                                  return(all_athletes)


                              def get_from_store():
                                  all_athletes = {}
                                    try:
                  Simply read the
                                        with open(‘athletes.pickle', ‘rb') as athf:
                  entire pickle into
                   the dictionary.                all_athletes = pickle.load(athf)
                   What could be                                                      Again…don’t
                   easier?          except IOError as ioerr:                          forget your

                                        print(‘File error (get_from_store): ' + str(ioerr))  try/except.

                                  return(all_athletes)


           224    Chapter 7
   255   256   257   258   259   260   261   262   263   264   265