ピクルスとシェルブの違いは何ですか?
-
29-09-2019 - |
質問
私は初めてオブジェクトのシリアル化について学んでいます。モジュールのピクルスと棚の違いについて、読んで「グーグル」を試してみましたが、理解していません。どちらを使用するのはいつですか?ピクルスは、すべてのPythonオブジェクトをファイルに持続できるバイトのストリームに変えることができます。では、なぜモジュールの棚が必要なのですか?ピクルスは速くなりませんか?
解決
pickle
一部のオブジェクト(またはオブジェクト)をファイル内の単一のバイテストリームとしてシリアル化するためです。
shelve
上に構築します pickle
オブジェクトがピクルスされているがキー(ある文字列)に関連付けられているシリアル化辞書を実装しているため、棚データファイルをロードしてキーを介してピクルスオブジェクトにアクセスできます。これは、多くのオブジェクトをシリアル化する方が便利です。
次に、2つの間の使用の例です。 (Python 2.7およびPython 3.xの最新バージョンで動作するはずです)。
pickle
例
import pickle
integers = [1, 2, 3, 4, 5]
with open('pickle-example.p', 'wb') as pfile:
pickle.dump(integers, pfile)
これにより捨てられます integers
呼ばれるバイナリファイルのリスト pickle-example.p
.
次に、ピクルスファイルを読んでみてください。
import pickle
with open('pickle-example.p', 'rb') as pfile:
integers = pickle.load(pfile)
print integers
上記は出力する必要があります [1, 2, 3, 4, 5]
.
shelve
例
import shelve
integers = [1, 2, 3, 4, 5]
# If you're using Python 2.7, import contextlib and use
# the line:
# with contextlib.closing(shelve.open('shelf-example', 'c')) as shelf:
with shelve.open('shelf-example', 'c') as shelf:
shelf['ints'] = integers
辞書のようなアクセスを介して棚にオブジェクトを追加する方法に注意してください。
次のようなコードでオブジェクトを読み戻します。
import shelve
# If you're using Python 2.7, import contextlib and use
# the line:
# with contextlib.closing(shelve.open('shelf-example', 'r')) as shelf:
with shelve.open('shelf-example', 'r') as shelf:
for key in shelf.keys():
print(repr(key), repr(shelf[key])))
出力はなります 'ints', [1, 2, 3, 4, 5]
.
所属していません StackOverflow