all Python 3Files & I/Oterm
pickle
pickle
Serialization of Python objects into a binary format. It stores arbitrary objects. Not safe for untrusted data!
Syntax
import pickle
pickle.dump(obj, f)
pickle.load(f)
The file must be opened in binary mode ('wb' for dump, 'rb' for load); plain 'w' raises TypeError. The format is Python-only and tied to your code: on load the classes must be importable under exactly the same module path as when they were saved, so renaming a module or class breaks old .pkl files — use JSON when the data has to travel to other programs.
Examples
import pickle, os, tempfile
data = {'key': [1,2,3], 'val': (4,5)}
path = os.path.join(tempfile.gettempdir(), 'data.pkl')
with open(path,'wb') as f:
pickle.dump(data, f)
with open(path,'rb') as f:
loaded = pickle.load(f)
print(loaded) # → {'key':[1,2,3],'val':(4,5)}
import pickle, os, tempfile
# dumps/loads — в bytes
bytes_data = pickle.dumps([1,'hello',3.14])
print(bytes_data[:10]) # → ? первые байты пикла, зависят от протокола
print(pickle.loads(bytes_data)) # → [1,'hello',3.14]
import pickle, os, tempfile
# Сериализация объекта класса
class Point:
def __init__(self,x,y): self.x=x;self.y=y
def __repr__(self): return f'Point({self.x},{self.y})'
p = Point(1,2)
bytes_p = pickle.dumps(p)
print(pickle.loads(bytes_p)) # → Point(1,2)
import pickle, os, tempfile
# Протоколы
print(pickle.HIGHEST_PROTOCOL) # → 5
bytes2 = pickle.dumps([1,2,3], protocol=2)
print(pickle.loads(bytes2)) # → [1,2,3]
import pickle, os, tempfile
# ВНИМАНИЕ: pickle небезопасен для чужих данных!
# Никогда не делай pickle.load() из ненадёжного источника!
See also
Open in the full glossarydocs.python.orgReport an inaccuracy