Page 172 -
P. 172

idle session







              pickle really shines when you load some previously pickled data into another program. And, of course, there’s
              nothing to stop you from using pickle with nester. After all, each module is designed to serve different
              purposes. Let’s demonstrate with a handful of lines of code within IDLE’s shell. Start by importing any required
              modules:
              >>> import pickle
              >>> import nester
              No surprises there, eh?
              Next up: create a new identifier to hold the data that you plan to unpickle.Create an empty list called new_man:
              >>> new_man = []

              Yes, almost too exciting for words, isn’t it? With your list created. let’s load your pickled data into it. As you are
              working with external data files, it’s best if you enclose your code with try/except:

              >>> try:
                     with open('man_data.txt', 'rb') as man_file:
                             new_man = pickle.load(man_file)
              except IOError as err:
                     print('File error: ' + str(err))
              except pickle.PickleError as perr:
                     print('Pickling error: ' + str(perr))

              This code is not news to you either. However, at this point, your data has been unpickled and assigned to the
              new_man list. It’s time for nester to do its stuff:
              >>> nester.print_lol(new_man)
              Is this the right room for an argument?
              No you haven’t!
                                                       Not all the data is shown
              When?                                   here, but trust us: it’s all
              No you didn’t!                          there.
                 ...
              You did just then!
              (exasperated) Oh, this is futile!!
              Yes it is!
              And to finish off, let’s display the first line spoken as well as the last:
              >>> print(new_man[0])
              Is this the right room for an argument?
              >>> print(new_man[-1])
              Yes it is!



                                See: after all that, it is the right room! §
           136    Chapter 4
   167   168   169   170   171   172   173   174   175   176   177