下面是关于 Python 序列化 pickle/cPickle 模块的使用介绍的详细攻略。
什么是pickle/cPickle模块?
Python提供了pickle/cPickle模块,可以将Python对象序列化成字节流用于传输和存储,并可以将序列化后的字节流反序列化成Python对象。pickle模块是Python内置的,而cPickle模块则是C语言写的快速版本。
pickle/cPickle模块常用方法
pickle.dump(obj, fileobj)
将obj序列化并写入 fileobj 文件对象。fileobj 必须是具有 write() 方法的二进制文件对象,例如打开的文件或 BytesIO。
import pickle
# 将对象序列化并写入文件
data = {'name': 'Tom', 'age': 20}
with open('example.pkl', 'wb') as f:
pickle.dump(data, f)
pickle.dumps(obj, protocol=None, *, fix_imports=True)
将 obj 序列化为字节流。protocol 是序列化协议的版本号,默认使用最高版本。fix_imports 为 Python 2 的兼容性设置,True 表示修正 Python 2 的导入错误。
import pickle
# 将对象序列化为字节流
data = {'name': 'Tom', 'age': 20}
pkl_data = pickle.dumps(data)
print(pkl_data)
pickle.load(fileobj)
从 fileobj 文件对象中读取序列化的对象,并将其反序列化为 Python 对象。fileobj 必须是具有 read() 方法的二进制文件对象,例如打开的文件或 BytesIO。
import pickle
# 从文件中读取序列化的对象
with open('example.pkl', 'rb') as f:
data = pickle.load(f)
print(data)
pickle.loads(bytes_object, *, fix_imports=True, encoding="ASCII", errors="strict")
从字节流 bytes_object 中反序列化对象,并将其转换为 Python 对象。fix_imports、encoding 和 errors 为 Python 2 的兼容性设置。
import pickle
# 从字节流中反序列化对象
pkl_data = b'\x80\x04\x95\x0b\x00\x00\x00\x00\x00\x00\x00}\x94(\x8c\x04name\x94\x8c\x03Tom\x94\x8c\x03age\x94K\x14\x86\x94u.'
data = pickle.loads(pkl_data)
print(data)
pickle/cPickle模块使用示例
下面我们通过对一个复杂数据对象进行序列化和反序列化的示例来详细介绍pickle/cPickle模块的使用方法。
示例1:使用pickle进行序列化和反序列化
1. 数据定义和对象初始化
import pickle
class Student(object):
def __init__(self, name="", age=0, gender="male"):
self.name = name
self.age = age
self.gender = gender
def set_name(self, name):
self.name = name
def set_age(self, age):
self.age = age
def set_gender(self, gender):
self.gender = gender
def display(self):
print("Name: ", self.name)
print("Age: ", self.age)
print("Gender: ", self.gender)
students = []
students.append(Student("Tom", 20, "male"))
students.append(Student("Lucy", 19, "female"))
2. 序列化并写入文件
with open("students.pkl", "wb") as f:
pickle.dump(students, f)
3. 从文件中读取序列化的对象并反序列化
with open("students.pkl", "rb") as f:
students = pickle.load(f)
for stu in students:
stu.display()
输出结果:
Name: Tom
Age: 20
Gender: male
Name: Lucy
Age: 19
Gender: female
示例2:使用cPickle进行序列化和反序列化
cPickle模块的使用与pickle几乎相同,只是将引用pickle模块改为cPickle模块即可。由于cPickle是C语言写的快速版本,因此在序列化和反序列化大量数据时速度要比pickle快得多。
1. 数据定义和对象初始化
import cPickle as pickle
class Book(object):
def __init__(self, title="", author="", publish_date=None):
self.title = title
self.author = author
self.publish_date = publish_date
def set_title(self, title):
self.title = title
def set_author(self, author):
self.author = author
def set_publish_date(self, publish_date):
self.publish_date = publish_date
def display(self):
print("Title: ", self.title)
print("Author: ", self.author)
print("Publish date: ", self.publish_date)
books = []
books.append(Book("Python学习指南", "George", "2020-01-01"))
books.append(Book("Java编程思想", "Bruce", "2019-12-01"))
books.append(Book("C++ Primer Plus", "Stanley", "2020-02-01"))
2. 序列化并写入文件
with open("books.pkl", "wb") as f:
pickle.dump(books, f)
3. 从文件中读取序列化的对象并反序列化
with open("books.pkl", "rb") as f:
books = pickle.load(f)
for book in books:
book.display()
输出结果:
Title: Python学习指南
Author: George
Publish date: 2020-01-01
Title: Java编程思想
Author: Bruce
Publish date: 2019-12-01
Title: C++ Primer Plus
Author: Stanley
Publish date: 2020-02-01
以上就是关于pickle/cPickle模块的使用介绍和示例,希望对大家有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python 序列化 pickle/cPickle模块使用介绍 - Python技术站