Hello!
I have a file with a list and 3 functions in it; view, append and sort functions.
I want to use pickle to save data changes in to another file inorder to retrive it next time.
I have a list, when i call function VIEW, i see the primary list i created. When i call APPEND function, i can append a new word and see it with print in that function. But if i call VIEW function again, i see the primary list again without any data changes (the append word).

I know i should use:

import pickle

pickle.dump(favorite_movies, open("films.db", "wb"))

favorite_movies = pickle.load( open("films.db", "rb"))

Correct?!

Now my problem is that where should i type pickle.dump and pickle.load in the main file.
In the first line above all codes?
Inside each function?
Or somewhere in this part:

if __name__ == "__main__":

    import argparse
    parser = argparse.ArgumentParser(description='Execute a function')
    parser.add_argument('funcname',
    help='name of function to execute',
    metavar='FUNCNAME',
    choices=['view' , 'sort' , 'append'])
args = parser.parse_args()
function = globals()[args.funcname]
function()

I'm almost new to programming, so this is the problem i have now with this little project.

Well, i solved the problem myself finally :)

I would use with, it closes your files properly. Also use a protocol for larger files:

import pickle

fname = "films.db"
with open(fname, "wb") as fout:
    # default protocol is zero
    # -1 gives highest prototcol and smallest data file size
    pickle.dump(favorite_movies, fout, protocol=-1)

# pickle load the object back in (senses protocol)
with open(fname, "rb") as fin:
    favorite_movies = pickle.load(fin)
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.