Oops

I've got my own wee dictionary reader, writers. Very simple -

So, you have a user Dave, who has a dictionary of {'address':'21 jump
St', 'Number: 'One, the loneliest.'}

So, you create a dictionary of dictionaries -myDict = {'Dave' :
{'address':'21 jump St', 'Number: 'One, the loneliest.'}

And then you have -
def writeDict(file, diction):
    inp=file(file, 'w')

    for (key, item) in diction.items():
      inp.write(key+'\n')
      inp.write(item+'\n')
    inp.close()

    return 1

Courtesy of Danny Yoo, the very helpful pair generating function below
(it's indispensable this one, I use it so often)

def groupAdjacentElements(someSequence, n = 2):
    """A little helper utility to group up adjacent elements."""
    nextGroup = []
    for element in someSequence:
        nextGroup.append(element)
        if len(nextGroup) == n:
            yield tuple(nextGroup)
            nextGroup = []

Goes with -

def loadDict(filename):
   store2 = file(filename,'r')

   for (name, entry) in groupAdjacentElements(store2):
     name = name.strip()
     entry = entry.strip()
     book[name] = entry

   store2.close()
   return book

So - to save myDict to saveddic.dct -

writeDict('saveddic.dct', myDict)

and to open it -

myDictCopy=loadDict('saveddic.dct')

And it saves in the format -

dave
{'address':'21 Jump St', 'number':'One, the loneliest'}
key
value
key
value

Nice and plaintext.

HTH




On Sun, 5 Dec 2004 16:31:59 -0500, Jacob S. <[EMAIL PROTECTED]> wrote:
> I did something like this about three or four months ago...
> This is what I did. Notice the use of the built-in str() and eval()
> functions to write and receive data to and from Telephone.cfg...
>
> from __future__ import division
> tel = {}
> try:
>     file = open('Telephone.cfg', 'r')
> except:
>     file = open('Telephone.cfg','w')
>     file.close()
>     file = open('Telephone.cfg','r')
> try:
>     tel = eval(file.read())
>     a = 0
> except:
>     a = 1
>     print "No entries on file."
>     pass
> print """\
> Commands are:
> add
> get
> save
> delete
> quit
> all is a wildcard
> """
>
> while 1:
>     ask = raw_input('Tell me what you wish to do. ')
>     if ask == "quit":
>         break
>     ask = ask.split(" ")
>     command = ask[0]
>     entity = ask[1:]
>     entity = " ".join(entity)
>     if entity == '':
>         entity = raw_input("Who do you want to %s? " % command)
>     if command == 'add':
>         person = entity
>         if tel.has_key(person):
>             print "That person is already in there. If you wish to edit the
> file, please delete the record first."
>         else:
>             tel[person] = raw_input("What is their phone number? ")
>     if command == 'get':
>         if a == 1:
>             print "Sorry, there are no entries available."
>         else:
>             person = entity
>             if person == 'all':
>                 key = tel.keys()
>                 key.sort()
>                 print
>                 for x in key:
>                     print "%s\n%s\n" % (x,tel[x])
>             elif tel.has_key(person):
>                 print "\n%s\n%s\n" % (person,tel[person])
>             else:
>                 print "%s is not in your records." % person
>     if command == 'save':
>         file=open('Telephone.cfg', 'w')
>         file.write(str(tel))
>         file.close()
>         print 'Saved in Telephone.cfg'
>     if command == 'delete':
>         if a == 1:
>             print "Sorry, there are no entries available."
>         else:
>             person = entity
>             if person == 'all':
>                 tel={}
>                 newfile=open('Telephone.cfg', 'w')
>                 newfile.close()
>             else:
>                 if tel.has_key(person):
>                     del tel[person]
>                 else:
>                     print "%s is not in your records." % person
> file.close()
> file = open('Telephone.cfg', 'w')
> file.write(str(tel))
> file.close()
>
> As always, feel free to modify, use, and otherwise tear apart my code and
> give me suggests on how to improve it.
> Jacob Schmidt
>
>
>
> > Dear Tutor,
> >
> > I like to know what is the proper procedure (is algorithmn the right
> > term?) in creating data in a program, write it to file, close the app
> > then retrieve the data when run again. Basically, I'm trying to simulate
> > a simple address book (well not really for the datas are just names for
> > now) and so far have created the basic menu interface. It is console
> > base so forget gui. I ask user input and store it in a list. There are
> > menus to change, delete the data, and to save the data list in file. I
> > use cPickle for this and have verified the file is created by checking
> > in my $PWD. I want to retrieve that data when program is run again. What
> > to add in my code? I thought not to post the code but explain it as
> > above.
> >
> > What i want: when program is run again, the saved data is loaded when user
> > selects option 1 below. Of course the first time it is run, the list is
> > empty.
> >
> > def print_options():
> >        print '''
> >        Options:
> >        [1] - Print content of list
> >        [2] - Add name to list
> >        [3] - Delete name from list
> >        [4] - Change name in list
> >        [5] - Save list to file
> >        [P] - Print this menu
> >        [Q] - Quit
> >        '''
> >
> >
> >
> > --
> > Regards,
> > Eri Mendz
> > Using PC-Pine 4.61
> >
> >
> > --
> > Using PC-Pine 4.61
> >
> > _______________________________________________
> > Tutor maillist  -  [EMAIL PROTECTED]
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
>
> _______________________________________________
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
>


--
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
_______________________________________________
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor

Reply via email to