Page 148 -
P. 148

save to disk




                                            At the bottom of your program, two calls to the print() BIF
                                            display your processed data on screen. You were to amend this
                                            code to save the data to two disk files instead.

                                            You were to call your disk files man_data.txt (for what the
                                             man said) and other_data.txt (for what the other man said).
                                            You were to make sure to both open and close your data files, as
                                             well as protect your code against an IOError using try/except.
                   man = []
                  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':                                      All of this code is
                                  man.append(line_spoken)                            unchanged.
                              elif role == 'Other Man':
                                  other.append(line_spoken)
                          except ValueError:
                              pass
                      data.close()
                  except IOError:
                                                                Did you remember to open
                      print('The datafile is missing!')
                                                                your files in WRITE mode?
                  try:
                       man_file = open(‘man_data.txt’, ‘w’)        Open your two files, and assign
                       other_file = open(‘other_data.txt’, ‘w’)    each to file objects.

                                   file=man_file
                      print(man,                 )               Use the “print()” BIF to save the
                                      file=other_file            named lists to named disk files.
                      print(other,                  )

                      man_file.close()          Don’t forget to close BOTH files.
                      other_file.close()
                  except IOError:                   Handle an I/O exception, should
                      print('File error.’)          one occur.




           112    Chapter 4
   143   144   145   146   147   148   149   150   151   152   153