Head Frost Python読書ノート第4章「漬け」データ

2683 ワード

Pythonは、リストを含むほとんどのPythonデータオブジェクトを保存およびロードできるPickleという標準ライブラリを提供しています.
また、公式ドキュメントでもPickleを用いた剣のシーケンス化処理が行われているほか、Pythonにはシーケンス化に利用できるmarshalがあるが、シーケンス化されたデータを再シーケンス化して認識できなくなり、ユーザーカスタムクラスのシーケンス化をサポートせず、バージョンが互換性がないなど、使いにくいようだ.
Python 3までです.4バージョン、picklingは0-4の5つのバージョンがあり、バージョンが高いほど、機能が強くなり、直接読むことができません.
  • 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. 

  • pickleには2つの主要な方法が含まれています
    pickle.dump(obj,file,protocol=None,*,fix_imports=True)保存データ
    pickle.load(file,*,fix_imports=True,encoding="ASCII",errors="strict")ロードデータ
    コード:
    #pickle test
    #to save and load data from disk with pickle
    import pickle
    #save data
    def save_data(data,file_name):
        try:
            with open(file_name,'wb') as file_out:
                pickle.dump(data,file_out)
        except pickle.PickleError as perr:
            print('Pickling error:'+str(perr))
    
    #load data
    def load_data(file_name):
        try:
            with open(file_name,'rb') as file_in:
                data=pickle.load(file_in)
                print(data)
        except pickle.PickleError as perr:
            print('Pickling error:'+str(perr))