删除或编辑使用Python pickle保存的条目
我基本上是进行一系列的导出和导入操作,但有时候我想删除其中一个已经导入的条目。我该怎么做呢?有没有办法删除或者编辑用Python的pickle/cpickle保存的条目?
补充说明:这些数据是用pickle保存在一个二进制文件里的。
1 个回答
9
要从一个二进制文件中删除一个被“腌制”的对象,你必须重写整个文件。因为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数据库可能是最好的选择。