Page 169 -
P. 169

persistence


           Save with dump and restore with load


           Using pickle is straightforward: import the required module, then use
           dump() to save your data and, some time later, load() to restore it. The
           only requirement when working with pickled files is that they have to be
           opened in binary access mode:

           Always           import pickle
           remember                ...
           to import
           the “pickle”     with open('mydata.pickle', 'wb') as mysavedata:                  The “b” tells
           module.                 pickle.dump([1, 2, 'three'], mysavedata)                   Python to open
          T o save your data,      ...                                                       your data files
           use “dump()”.    with open('mydata.pickle', 'rb') as myrestoredata:               in BINARY
                                                                                             mode.
                                   a_list = pickle.load(myrestoredata)
             Assign your
             restored data   print(a_list)                    file using “load()”.
                                                              Restore your data from your
              to an identifier.

                 Once your data is back in your program, you can
                 treat it like any other data object.


           What if something goes wrong?

           If something goes wrong when pickling or unpickling your data, the pickle
           module raises an exception of type PickleError.




             w                                  Here’s a snippet of your code as it currently stands. Grab your
                                                pencil and strike out the code you no longer need, and then
                                                replace it with code that uses the facilities of pickle instead.
                                                Add any additional code that you think you might need, too.


                 try:
                     with open('man_data.txt', 'w') as man_file, open('other_data.txt', 'w') as other_file:
                         nester.print_lol(man, fh=man_file)
                         nester.print_lol(other, fh=other_file)
                 except IOError as err:
                     print('File error: ' + str(err))





                                                                                      you are here 4    133
   164   165   166   167   168   169   170   171   172   173   174