【问题标题】:Remove or edit entry saved with Python pickle删除或编辑使用 Python pickle 保存的条目
【发布时间】:2013-02-13 09:49:09
【问题描述】:

我基本上会执行转储和加载序列,但有时我想删除其中一个加载的条目。我怎样才能做到这一点?有没有办法删除或编辑使用 Python pickle/cpickle 保存的条目?

编辑:数据与pickle一起保存在二进制文件中。

【问题讨论】:

  • 您是如何保存这些项目的?在文件上?另外,到目前为止,您尝试过什么?
  • 是的,它们保存在一个文件中
  • @Alex 据我了解,您希望能够从文件中的任意位置删除。但是,这将要求您再次写入整个文件。如果您不习惯重写整个文件,请考虑使用 SQLite(最少的工作量)作为文件的替代方案。
  • @Alex:那么你需要更复杂的东西。要么使用 SQL 数据库,要么使用 ZODB(可以处理更细粒度的酸洗)。
  • @Alex 是的。我用 MySQL 试过了,效果很好。像pickle.loads(b64decode(value))unicode(b64encode(pickle.dumps(value, pickle.HIGHEST_PROTOCOL))) 这样的东西可以解决问题。这似乎也涵盖了它 - stackoverflow.com/questions/8150078/…

标签: python binary pickle


【解决方案1】:

要从二进制文件中删除腌制对象,您必须重写整个文件。 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 数据库可能是最好的选择。

【讨论】:

  • 谢谢!唯一的缺点是 [shelve] 很慢,但可能不会比重写整个文件慢。
  • @Alex 我不确定,但可能使用update 方法而不是一个一个地设置键可能会更快(因为这有机会进行单个批量事务而不是多个写)。
  • 所以这应该适用于腌制的物体?在我的情况下不起作用:dbm.error: db type could not be determined
  • @CGFoX 这似乎是一个损坏的数据库文件。无论如何,您应该尝试对此提出自己的问题。
猜你喜欢
  • 1970-01-01
  • 2021-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-08
  • 1970-01-01
相关资源
最近更新 更多