python - 删除或编辑用 Python pickle 保存的条目

标签 python binary pickle

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

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

最佳答案

要从二进制文件中删除 pickled 对象,您必须重写整个文件。 pickle 模块不处理流的任意部分的修改,因此没有内置方法来执行您想要的操作。

可能最简单的二进制文件替代方法是使用 shelve模块。

这个模块提供了一个类似 dict 的接口(interface)到包含 pickled 数据的数据库,正如您从文档中的示例中看到的那样:

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 数据库可能是最佳选择。

关于python - 删除或编辑用 Python pickle 保存的条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15114616/

相关文章:

python - 如何从 ASCII 文件绘制波长与通量的关系图

python - 为什么 Python 为短于文件系统限制的文件名给出 "OSError: [Errno 36] File name too long"?

c++ - 将整数写入二进制文件 C++ 的问题

php - 读取文件的二进制代码...在 PHP 中

python-3.x - Python 类型、pickle 和序列化

python - 可以 pickle cookiejar 对象吗?

python - 如何使用 python zipfile 库检查 zip 文件是否拆分为多个存档?

python - 正则表达式查找句子中的首字母缩写

Java从很长的范围内获取位范围

python - pickle 内部类