Member Avatar for leegeorg07

hi im trying to expand on my dictionary learning and i currently have two problems with this code:

import cPickle
file = open('phonebook.txt', 'w')

phonebook = {'Andrew Parson':8806336, \
'Emily Everett':6784346, 'Peter Power':7658344, \
'Lewis Lame':1122345}

cPickle.dump(phonebook,file)

raw_input("press enter to show how to add a key and a value")

phonebook['Ginger' ] = 1234567

cPickle.dump(phonebook,file)

print phonebook

p = float(raw_input("do you want to add a new person? (1 = yes, 0 = no)"))
s = float(raw_input("do you want to stay? (again 1 = yes, 0 = no)"))
if s == 1:
    if p == 1:
        n = raw_input("what is the persons name?")
        nb = raw_input("what is there number?")
        phonebook[n] = nb
        cPickle.dump(phonebook,file)
        v = float(raw_input("do you want to see the phonebook now? (1 = yes, 0 = no)"))
        if v == 1:
              print phonebook
        else:
            print "thank you for using a George Lee program"
            raw_input("press enter to close")

    else:
        print "thank you for using a George Lee program"
        raw_input("press enter to close")
else:
    print "thank you for using a George Lee program"
    raw_input("press enter to close")

print "thank you for using a George Lee program"
g =  float(raw_input("are you sure you want to go? (again 1 = yes, 0 = no)"))
if g == 0:
    if p == 1:
        n = raw_input("what is the persons name?")
        nb = raw_input("what is there number?")
        phonebook[n] = nb
        cPickle.dump(phonebook,file)
        v = float(raw_input("do you want to see the phonebook now? (1 = yes, 0 = no)"))
        if v == 1:
              print phonebook
        else:
            print "thank you for using a George Lee program"
            raw_input("press enter to close")

    else:
        print "thank you for using a George Lee program"
        raw_input("press enter to close")

file.close()

first of all how can i make the txt file (phonebook.txt) easily readable?
secondly how can i edit the code so that it uses phonebook.txt as the dictionary phonebook
any help and advice welcome thanks

If you want to store the notebook in a readable form, a good solution could be pretty-print the dictionary to the file without using the cPickle module. You would have two functions

from pprint import pprint
TXTFILE = "notebook.txt"

def dump_notebook(notebook):
  fout = open(TXTFILE, "w")
  pprint(notebook, fout)
  fout.close()

def load_notebook():
  fin = open(TXTFILE, "r")
  dic = eval(fin.read())
  fin.close()
  return dic

Also you could structure your program like this

def user_interaction(notebook):
  ... # raw inputs and user requests

def main():
  notebook = load_notebook()
  try:
    user_interaction(notebook)
  finally:
    dump_notebook(notebook)

main()

With this structure, you would be sure that the notebook is save to the file when the program exits, even if something fails in the interaction with the user.

Actually the module shelve works better with dictionaries:

# save and retrieve data via a shelve byte stream file
# creates a 'persistent to file' dictionary

import shelve

phonebook = {
'Andrew Parson': 8806336,
'Emily Everett': 6784346, 
'Peter Power': 7658344,
'Lewis Lame': 1122345
}

# dictionary data will be in a shelve byte stream file
shlv2 = shelve.open('phonebook.slv')

phonebook['Ginger Roger'] = 1234567

# this will save all current phonebook data 
# access key will "phone_dict"
shlv2["phone_dict"] = phonebook

phonebook['Larry Lark'] = 9234568

# you can update again before you close
shlv2["phone_dict"] = phonebook
shlv2.close()

print '-'*50

# testing ...
# this could be a second program ...
# retrieve the saved data from the file
shlv3 = shelve.open('phonebook.slv')
#print shlv3.keys()
# use the access key "phone_dict"
# notice that this loads right into a dictionary
phonebook2 = shlv3["phone_dict"]
print phonebook2

print '-'*50

print phonebook2['Lewis Lame']
print phonebook2['Larry Lark']
print phonebook2['Ginger Roger']

shlv3.close()
Member Avatar for leegeorg07

thanks for the posts and griboullis' idea seems easier but i dont really understand the def function :( (i kind of skipped that part) so could you explain them and also possibly explain the prettyprint module

If you don't understand well the def (function definitions) in python, I suggest that you read this http://www.openbookproject.net/thinkCSpy/ch03.xhtml.

About the functions I wrote above, I defined 4 functions
* dump_notebook(notebook), which takes a dictionary argument, and pretty-prints the dictionary in the file notebook.txt when it is called.
*load_notebook() which reads the file notebook.txt (assumed to contain a dictionary. Initially, you could put just {} in that file) and evaluates the content of this file to obtain a python dictionary object, which is returned.
*user_interaction(notebook) The body of this function should contain all that you need in order to interact with the user during the execution of the program (the raw_input's, the modification of the content of the dictionary). You don't need the file during this function. You just use the dictionary object
*main() A main function which, when called, loads the notebook from the file, calls user_interaction, and finally dumps the (possibly modified) dictionary to the file.

main() is called as the last statement of the program. I hope this explains a little :)

Member Avatar for leegeorg07

thanks i understand it better now but the document will me called phonebook.txt and also if possible could you show me how i could incorporate it into my existing code (my first post)

Member Avatar for leegeorg07

thanks for the pm griboullis but im having a bit of trouble

this is my code:

from pprint import pprint
TXTFILE = "phonebook.txt"

def dump_notebook(phonebook):
  fout = open(TXTFILE, "w")
  pprint(notebook, fout)
  fout.close()

def load_notebook():
  fin = open(TXTFILE, "r")
  dic = eval(fin.read())
  fin.close()
  return dic

def user_interaction(phonebook):
phonebook = {'Andrew Parson':8806336, \
'Emily Everett':6784346, 'Peter Power':7658344, \
'Lewis Lame':1122345}

raw_input("press enter to show how to add a key and a value")

phonebook['Ginger' ] = 1234567

print phonebook

p = float(raw_input("do you want to add a new person? (1 = yes, 0 = no)"))
s = float(raw_input("do you want to stay? (again 1 = yes, 0 = no)"))
if s == 1:
    if p == 1:
        n = raw_input("what is the persons name?")
        nb = raw_input("what is there number?")
        phonebook[n] = nb
        v = float(raw_input("do you want to see the phonebook now? (1 = yes, 0 = no)"))
        if v == 1:
              print phonebook
        else:
            print "thank you for using a George Lee program"
            raw_input("press enter to close")

    else:
        print "thank you for using a George Lee program"
        raw_input("press enter to close")
else:
    print "thank you for using a George Lee program"
    raw_input("press enter to close")

print "thank you for using a George Lee program"
g =  float(raw_input("are you sure you want to go? (again 1 = yes, 0 = no)"))
if g == 0:
    if p == 1:
        n = raw_input("what is the persons name?")
        nb = raw_input("what is there number?")
        phonebook[n] = nb
        v = float(raw_input("do you want to see the phonebook now? (1 = yes, 0 = no)"))
        if v == 1:
              print phonebook
        else:
            print "thank you for using a George Lee program"
            raw_input("press enter to close")

    else:
        print "thank you for using a George Lee program"
        raw_input("press enter to close")

def main():
    notebook = load_phonebook()
    try:
        user_interaction(phonebook)
    finally:
        dump_phonebook(phonebook)

main()

when i run it nothing happens. how can i fix this

first replace ALL the occurences of notebook by phonebook. Then the code you put in the function user_interaction must be INDENTED (like in a if statement). Also you should drop the initial assignment phonebook = {...} . Insted, you could put the part {...} in an initial phonebook.txt file.
Next: use your head, and python's error messages!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.