Python Persistence

suggest change

Objects like numbers, lists, dictionaries,nested structures and class instance objects live in your computer’s memory and are lost as soon as the script ends.

pickle stores data persistently in separate file.

pickled representation of an object is always a bytes object in all cases so one must open files in wb to store data and rb to load data from pickle.

the data may may be off any kind , for example,

data={'a':'some_value',
     'b':[9,4,7],
     'c':['some_str','another_str','spam','ham'],
     'd':{'key':'nested_dictionary'},
     }

Store data

import pickle
file=open('filename','wb')  #file object in binary write mode
pickle.dump(data,file)      #dump the data in the file object
file.close()                #close the file to write into the file

Load data

import pickle
file=open('filename','rb')  #file object in binary read mode
data=pickle.load(file)      #load the data back
file.close()

>>>data
{'b': [9, 4, 7], 'a': 'some_value', 'd': {'key': 'nested_dictionary'},
 'c': ['some_str', 'another_str', 'spam', 'ham']}

The following types can be pickled

  1. None, True, and False
  2. integers, floating point numbers, complex numbers
  3. strings, bytes, bytearrays
  4. tuples, lists, sets, and dictionaries containing only picklable objects
  5. functions defined at the top level of a module (using def, not lambda)
  6. built-in functions defined at the top level of a module
  7. classes that are defined at the top level of a module
  8. instances of such classes whose dict or the result of calling getstate()

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Persistence with pickle:
* Python Persistence

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
150 Persistence with pickle
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve