Neat Python Feature - Pickle!

Words
228
Reading
2 min
Listen
Play
9y

persist.png

Back when I was learning C and C++, I often reused a piece of code that would write data from memory to a file and read it back again to persist state.

Just dump my struct to a file.

Any time the software needed to restart - say after a system crash - it could just keep on trugging along as if not much had happened :)

It is a very long time since I coded in C++ (outside of Arduino and C#) but that concept stuck with me.

I had no idea there was a similar functionality in Python until today (yes, I am late to the party!)

Introducing Pickle

Now if this is not news to you I do not blame you for rolling your eyes, but if you haven't seen Pickle then you are in for a treat.

Start with, as you would expect, importing pickle.

Then use the following code to persist and recall your data:

def persist(item_list):

    with open('my_list.txt', 'wb') as fp:
        pickle.dump(item_list, fp)

Supply this function with your array/list.

And then to get it back ...

def retrieve():

    item_list = []

    try:

        with open('my_list.txt', 'rb') as fp:
            item_list = pickle.load(fp)
    except:
        print("Pickle bork - ah well!")

    return item_list

So what happens is your array or list goes from memory to a file on your file system, and then you can reverse the process :)

Obviously the file needs to exist, so just use the shell command as follows:

touch my_list.txt

(this will create a placeholder file ready for your script to run)

Neat, eh?

Neat Python Feature - Pickle! | Ecency