删除或编辑用Python pi保存的条目

2024-06-17 14:55:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我基本上是做转储和加载的序列,但是在某个时刻我想删除一个加载的条目。我该怎么做?是否有方法删除或编辑用Python pickle/cpickle保存的条目?

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


Tags: 文件数据方法编辑二进制条目序列pickle
1条回答
网友
1楼 · 发布于 2024-06-17 14:55:39

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

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

这个模块提供了一个类似于dict的接口,该接口指向包含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数据库可能是最好的选择。

相关问题 更多 >