2021-05-12 14:32:11
Python pickle模組常用方法程式碼範例
2020-10-10 15:00:02
用於序列化的兩個模組
- json:用於字串和Python資料型別間進行轉換
- pickle: 用於python特有的型別和python的資料型別間進行轉換
- json提供四個功能:dumps,dump,loads,load
- pickle提供四個功能:dumps,dump,loads,load
pickle可以儲存什麼型別的資料呢?
- 所有python支援的原生型別:布林值,整數,浮點數,複數,字串,位元組,None。
- 由任何原生型別組成的列表,元組,字典和集合。
- 函數,類,類的範例
pickle模組中常用的方法有:
1. pickle.dump(obj, file, protocol=None,)
必填引數obj表示將要封裝的物件
必填引數file表示obj要寫入的檔案物件,file必須以二進位制可寫模式開啟,即「wb」
可選引數protocol表示告知pickler使用的協定,支援的協定有0,1,2,3,預設的協定是新增在Python 3中的協定3。
- Protocol version 0 is the original 「human-readable」 protocol and is backwards compatible with earlier versions of Python.
- Protocol version 1 is an old binary format which is also compatible with earlier versions of Python.
- Protocol version 2 was introduced in Python 2.3. It provides much more efficient pickling of new-style classes. Refer to PEP 307 for information about improvements brought by protocol 2.
- Protocol version 3 was added in Python 3.0. It has explicit support for bytes objects and cannot be unpickled by Python 2.x. This is the default protocol, and the recommended protocol when compatibility with other Python 3 versions is required.
- Protocol version 4 was added in Python 3.4. It adds support for very large objects, pickling more kinds of objects, and some data format optimizations. Refer to PEP 3154 for information about improvements brought by protocol 4.
2. pickle.load(file,*,fix_imports=True, encoding="ASCII", errors="strict")
必填引數file必須以二進位制可讀模式開啟,即「rb」,其他都為可選引數
3. pickle.dumps(obj):以位元組物件形式返回封裝的物件,不需要寫入檔案中
4. pickle.loads(bytes_object): 從位元組物件中讀取被封裝的物件,並返回
pickle模組可能出現三種異常:
1. PickleError:封裝和拆封時出現的異常類,繼承自Exception
2. PicklingError: 遇到不可封裝的物件時出現的異常,繼承自PickleError
3. UnPicklingError: 拆封物件過程中出現的異常,繼承自PickleError
應用:
# dumps功能 import pickle data = ['aa', 'bb', 'cc'] # dumps 將資料通過特殊的形式轉換為只有python語言認識的字串 p_str = pickle.dumps(data) print(p_str) 7 b'x80x03]qx00(Xx02x00x00x00aaqx01Xx02x00x00x00bbqx02Xx02x00x00x00ccqx03e.
# loads功能 # loads 將pickle資料轉換為python的資料結構 mes = pickle.loads(p_str) print(mes) ['aa', 'bb', 'cc']
# dump功能 # dump 將資料通過特殊的形式轉換為只有python語言認識的字串,並寫入檔案 with open('D:/tmp.pk', 'w') as f: pickle.dump(data, f)
# load功能 # load 從資料檔案中讀取資料,並轉換為python的資料結構 with open('D:/tmp.pk', 'r') as f: data = pickle.load(f)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援it145.com。
相關文章