基本的にダンプとロードのシーケンスを実行しますが、ある時点で、ロードされたエントリの1つを削除したいと思います。どうやってやるの?Python pickle / cpickleで保存されたエントリを削除または編集する方法はありますか?
編集:データはpickleでバイナリファイルに保存されます。
ピクルス化されたオブジェクトをバイナリファイルから削除するには、ファイル全体を書き直す必要があります。このpickle
モジュールは、ストリームの任意の部分での変更を処理しないため、必要な処理を行うための組み込みの方法はありません。
おそらく、バイナリファイルの最も簡単な代替手段は、shelve
モジュールを使用することです。
このモジュールはdict
、ドキュメントの例からわかるように、ピクルス化されたデータを含むデータベースへの同様のインターフェイスを提供します。
import shelve
d = shelve.open(filename) # open -- file may get suffix added by low-level
# library
d[key] = data # store data at key (overwrites old data if
# using an existing key)
data = d[key] # retrieve a COPY of data at key (raise KeyError if no
# such key)
del d[key] # delete data stored at key (raises KeyError
# if no such key)
flag = key in d # true if the key exists
klist = list(d.keys()) # a list of all existing keys (slow!)
# as d was opened WITHOUT writeback=True, beware:
d['xx'] = [0, 1, 2] # this works as expected, but...
d['xx'].append(3) # *this doesn't!* -- d['xx'] is STILL [0, 1, 2]!
# having opened d without writeback=True, you need to code carefully:
temp = d['xx'] # extracts the copy
temp.append(5) # mutates the copy
d['xx'] = temp # stores the copy right back, to persist it
# or, d=shelve.open(filename,writeback=True) would let you just code
# d['xx'].append(5) and have it work as expected, BUT it would also
# consume more memory and make the d.close() operation slower.
d.close() # close it
使用されるデータベースは、プラットフォームと使用可能なライブラリに応じて、ndbm
またはです。gdbm
注:これは、データが他のプラットフォームに移動されていない場合にうまく機能します。データベースを他のコンピューターにコピーできるようにしたい場合はshelve
、どのライブラリが使用されるかについての保証がないため、うまく機能しません。この場合、明示的なSQLデータベースを使用するのがおそらく最良のオプションです。