Page 147 -
P. 147

persistence




                                                At the bottom of your program, two calls to the print() BIF
                                                display your processed data on screen. Let’s amend this code to
                                                save the data to two disk files instead.
                                                Call your disk files man_data.txt (for what the man said) and
                                                other_data.txt (for what the other man said). Be sure to
                                                both open and close your data files, as well as protect your code
                   man = []                     against an IOError using try/except.
                   other = []


                   try:
                       data = open('sketch.txt')
                       for each_line in data:
                           try:
                               (role, line_spoken) = each_line.split(':', 1)
                               line_spoken = line_spoken.strip()
                               if role == 'Man':
                                   man.append(line_spoken)
                               elif role == 'Other Man':
                                   other.append(line_spoken)
                           except ValueError:
                               pass
                       data.close()
                   except IOError:
                       print('The datafile is missing!')
           Go on, try.                                                     Open your two
                                                                           data files here.





                       print(man,                  )              Specify the files to
                       print(other,                   )           write to when you invoke
            Be sure to                                           “print()”.
            close your
            files.

                                                            Handle any
                                                            exceptions here.




                                                                                      you are here 4    111
   142   143   144   145   146   147   148   149   150   151   152