以前沒有學類的時候,數據存儲都是自己設計,按照對應的格式,使用pickle可以將數據以類的方式存儲
官方解釋:
The pickle module implements binary protocols for serializing and de-serializing a Python object structure. “Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream (from a binary file or bytes-like object) is converted back into an object hierarchy. Pickling (and unpickling) is alternatively known as “serialization”, “marshalling,” [1] or “flattening”; however, to avoid confusion, the terms used here are “pickling” and “unpickling”.
翻譯:
該pickle模塊實現了用於序列化和反序列化Python對象結構的二進制協議。 “Pickling”是將Python對象層次結構轉換爲字節流的過程, “unpickling”是相反的操作,即字節流(來自二進制文件或類似字節的對象)被轉換回對象層次結構。酸洗(與在unpickle)可替代地被稱爲“序列”,“編組” [1]或“壓扁”; 然而,爲了避免混淆,這裏使用的術語是“酸洗”和“不沾”。
pickle不會判斷語句的危險性,所以使用pickle需要注意
類似於json模塊,可以將數據導入到文件中,進行持久化(斷電不丟失數據)
pickle是將python類型進行序列化,使python的數據能得到持久化,思想就是將python內存中的內容保存到磁盤中,防止斷電消失。使程序可靠性能提高
簡單入門使用
import pickle
dic = {
'key1': 'value1',
'key2': 'value2',
'key3': 'value3',
}
f1 = open('pickle_file', 'wb')
pickle.dump(dic, f1)
f1.close()
with open('pickle_file', 'rb') as f2:
dic2 = pickle.load(f2)
print(dic2)
執行結果:
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
簡單項目應用
import pickle
class Course:
def __init__(self, name, period, price, school):
self.name = name # 課程名
self.period = period # 課程週期
self.price = price # 課程價格
self.school = school # 課程所屬的學校
# 創建3個對象
python = Course('python', '6month', 19800, '北京校區')
linux = Course('linux', '5 month', 12800, '北京校區')
go = Course('go', '4 month', 9800, '上海校區')
# 將對象多次寫入文件
with open('course_obj', 'ab') as f:
pickle.dump(python, f)
pickle.dump(linux, f)
pickle.dump(go, f)
# 將多個對象讀取出來,使用try方法死循環break
def loaditer(filename):
with open('course_obj', 'rb') as f:
while True:
try:
obj = pickle.load(f)
yield obj
except:
break
# 將執行的結果賦值,這裏yield的結果是一個生成器(地址)
load_g = loaditer('course_obj')
print('load_g 結果:', load_g)
for course_obj in load_g:
for i in course_obj.__dict__:
print(i, course_obj.__dict__[i])
print('-' * 50)
執行結果:
load_g 結果: <generator object loaditer at 0x030E5F30>
name python
period 6month
price 19800
school 北京校區
--------------------------------------------------
name linux
period 5 month
price 12800
school 北京校區
--------------------------------------------------
name go
period 4 month
price 9800
school 上海校區
--------------------------------------------------
利用生成器可以減少內存的使用,不會因爲數據量太大,撐爆內存
因爲傳入的對象數量不多,不會影響執行的速度效率,所以可以使用循環讀這種方法