FANDOM


Pickle Library Edit

The pickle library in Python allows you to write and read objects into binary files.

It us used for serializing and de-serializing a Python object structure. Any object in Python can be pickled so that it can be saved on disk. What pickle does is that is "serialises" the object first before writing it to a file. Pickling is a way to convert a python object (list, dict, ect.) into a character stream. The idea is that this character stream contains all the information necessary to reconstruct the object in another python script.

Some of the types that can be pickled and unpickled include:

  • None, True, and False
  • integers, long integers, floating point numbers, complex numbers
  • normal and unicode strings
  • tuples, lists, sets, and dicitonaries that hold picklable objects
  • functions defined at the top level of a module

and more. The complete list of picklable objects can be found HERE .

Example of picklingEdit

import pickle

f = open("pickles.txt, "bw")

myList = ["a", "b", "c"]
pickle.dump(myList, f)

f.close()

Example of unpicklingEdit

import pickle

f = open("pickles.txt", "br")

myList = pickle.load(f)
print(myList)

f.close()


Pickle has two main methods; dump, which dumps an object to a file object. And load, which loads an object from a file object. 

Shelve LibraryEdit

Shelving lets you store data in files in a dictionary-like structure.

The shelve module implements persistent storage for arbitrary Python objects which can be pickled, using a dictionary-like API.

The keys must be strings, the value can be any pickleable object.

The shelf is accessed by keys, just as with a dictionary. The values are pickled and written to a database created and managed by anydbm .

Example of shelvingEdit

import shelve

s = shelve.open("myquotes")
s["flowers"] = (0, 2, 3)

s.close()

This will create a file named "myquotes.db" and will write the data into it.

>>> s["slowers"]
(0, 2, 3)

>>> "flowers" in s
True

ReferencesEdit

Pickling and Shelving

What can be pickled and unpickled? - docs.python.org

What is Pickle in python? - pythontips.com

pickle - Python object serialization - docs.python.org

shelve - Persistent storage of arbitrary Python objects - PyMOTW

Community content is available under CC-BY-SA unless otherwise noted.