[Tutor] Saving and loading data to/from files

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


Daryl G wrote
> 
> Hi,  I am having difficulty in saving and loading data that I created in a 
> simple Address book program. I  am using 3 list variables for First and Last 
> name and phone number and an interger that counts the total number of 
> entries.  I first tried using the 'write' but that wouldn't work with lists. 
> I discovered the pickle module and
> I am able to save my data, but when I load it back up and then try to view 
> it in my program, its not there.
> 
> variables
> import pickle, string
> 
> F_Name=[]
> L_Name=[]
> PH_num=[]
> total=0
> 
> #savedata method
> def savedata():
>     filename= raw_input("Enter the name you wish to give this address book: 
> ")
>     object=(F_Name, L_Name, PH_num, total)
>     file=open(filename, 'w')
>     pickle.dump(object, file)
> 
> #opendata method
> def opendata():
>     filename=raw_input("Enter the name of the Addressbook you wish to open: 
> ")
>     file = open(filename,'r')
>     (F_Name,L_Name, PH_num, total)=pickle.load(file)
> 
> 
> What am I doing wrong?

You are assigning to local variables in opendata() when the variables
are global in savedata.  However you might want to think about passing
values, especially removing the raw_input() calls from the functions.

def opendata(filename):
  global F_Name, L_Name, PH_num, total
  file = open(filename, 'r')
  (F_Name, L_Name, PH_num, total) = pickle.load(file)

Or better yet, returning the values:
def opendata(filename):
  file = open(filename, 'r')
  # assigning to all values catches the error of invalid data format
  (F_Name, L_Name, PH_num, total) = pickle.load(file)
  return (F_Name, L_Name, PH_num, total)

Pickle is fine for outputting single values, but for a database of
values (like an address) you will want to look at the shelve module
(which uses pickle and the *dbm modules, see "anydbm") or a relational
database (which could be overkill for an address book application).

> Another question that I have is how do I format data that I want to display 
> in specific
> columns in standerd output, like that can be done in C ?

This is done with the string % operator.  With an order sequence:
  print '''Name: %s %s; Phone: %s''' % (F_Name, L_Name, PH_num)
or with a dictionary:
  print '''Name: %(first)s %(last)s; Phone: %(phone)s''' % {
    'first': F_Name, 'last': L_Name, 'phone': PH_num
  }

The Python Library documention has all this.  Much of it is actually
like C's sprintf.
<URL: http://www.python.org/doc/current/lib/typesseq-strings.html>

  -Arcege

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