all Python 3picklefunction
pickle.load()
deserialization
Reads one pickled object from a binary file. Warning: loading untrusted data executes arbitrary code.
Syntax
obj = pickle.load(file, *, fix_imports=True, encoding='ASCII', errors='strict', buffers=None)
The danger is not theoretical: pickle calls functions recorded in the stream while loading, and a crafted file runs a system command before you ever see the object. So load is only for files your own program wrote; use json for outside data. One call reads one object: if dump was called several times, read in a loop until EOFError. Open the file with 'rb'.
Examples
import pickle
with open('log.pkl', 'wb') as f:
for n in range(3):
pickle.dump({'n': n}, f)
records = []
with open('log.pkl', 'rb') as f:
while True:
try:
records.append(pickle.load(f))
except EOFError:
break
print(records) # → [{'n': 0}, {'n': 1}, {'n': 2}]
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy