1

I've been trying to make a quote input that puts multiple quotes inside a file (coupled with the authors name). I have tried with pickle, but I could not get more than 2 pickled items inside a file and finally I decided to use shelf.

However, I am having some trouble with shelves as well.

I dont really know how to put multiple items inside a file, even if I can shelf one.

import pickle
import shelve

quote = []
author = []

def givequote():

    f = shelve.open('quotation')
    ## open the shelve so that i can write stuff in it

    f["quote"] = raw_input("What quote has its place in the quote book? \n to quit press Q\n\n")
    ## ask for input so that i can put stuff into quote,  
   ##quote is a random value so its a problem, i might have to make a key/value first.
    if quote != "Q":
        f['author'] = raw_input("what author said that? \n to quit press Q \n\n")
        if author == "Q":
            print "goodbye"
    elif quote == "Q":
        print "goodbye"
    f.close()

def readquote():
    f = shelve.open('quotation')
    print "%3s\n - %s" % (f["quote"], f['author'])

thank you.

After finding out how it works I plan to try to make the same program using classes ( was thinking of nested ones) and methods, just to practice figuring out my inner programmer.

TTdream
  • 89
  • 1
  • 4

1 Answers1

0

You can do this with pickle. As this answer describes, you can append a pickled object to a binary file using open with append in binary mode.

To read the multiple pickled objects out of the file, just call pickle.load on the file handle until you get an EOF error.

so your unpickle code might look like

import pickle
objs = []
while 1:
  try:
    objs.append(pickle.load(f))
  except EOFError:
    break
Community
  • 1
  • 1
Karl
  • 315
  • 2
  • 9