簡體   English   中英

刪除或編輯使用Python泡菜保存的條目

[英]Remove or edit entry saved with Python pickle

我基本上會執行轉儲和加載的序列,但是在某些時候我想刪除已加載的條目之一。 我怎樣才能做到這一點? 有沒有辦法刪除或編輯用Python pickle / pickckle保存的條目?

編輯:數據用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

使用的數據庫是ndbmgdbm ,取決於平台和可用的庫上。

注意:如果數據未移動到其他平台,則此方法效果很好。 如果您希望能夠將數據庫復制到另一台計算機,則shelve無法很好地工作,因為它不能保證將使用哪個庫。 在這種情況下,使用顯式SQL數據庫可能是最佳選擇。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM