[Tutor] Saving and loading data to/from files

Michael P. Reilly arcege@speakeasy.net
Sun, 3 Jun 2001 17:09:07 -0400 (EDT)


Daryl G wrote
> That was it, though I did have to do it a little differently.
> The way you showed didn't seem to work with lists, so I just converted each 
> individual part of a list into a String and then it  worked
> 
>    for i in range(total):
>       LN=L_Name[i]
>       FN=F_Name[i]
>       PH=PH_num[i]
>       print"%-15.15s %-15.15s %-s" % (LN, FN, PH)

Sorry, I hadn't quite gotten that they were lists (I haven't really been
feeling "with it" lately).

You might find it easier to keep things together.  Create tuples with
the information, then arrays of those tuples.
NameInfo = [
  ('Guido', 'van Rossum', '703-555-1234'),
  ('Eric', 'Idle', '212-555-5346'),
]
for i in range(len(NameInfo)):
  (FN, LN, PH) = NameInfo[i]
  print "%-15.15s %-15.15s %s" % (LN, FN, PH)

This will allow for keeping things together later, and for better
looping structures: `for (FN, LN, PH) in NameInfo:'


Alternatively, you could use a dictionary for records of "named" fields:
NameInfo = [
  {'first': 'Guido', 'last': 'van Rossum', 'phone': '703-555-1234'},
  {'first': 'Eric', 'last': 'Idle', 'phone': '212-555-5346'},
]
for record in NameInfo:
  print "%-15.15(last)s %-15.15(first)s %(phone)s" % record


Or maybe make a class:
class Record:
  def __init__(self, first, last, phone):
    self.first, self.last, self.phone = first, last, phone
  def __str__(self):
    return '%-15.15s %-15.15s %s' % (self.last, self.first, self.phone)
NameInfo = [
  Record('Guido', 'van Rossum', '703-555-1234'),
  Record('Eric', 'Idle', '212-555-5346'),
]
for record in NameInfo:
  print record

There are a lot of choices for you, but separate lists for each field
probably isn't a good one. :) (Incidently, the pickle and shelve modules
handle all these structures)

  -Arcege

-- 
+----------------------------------+-----------------------------------+
| Michael P. Reilly                | arcege@speakeasy.net              |