删除或编辑条目保存泡菜的Python [英] Remove or edit entry saved with Python pickle

查看:317
本文介绍了删除或编辑条目保存泡菜的Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上做的转储和装载的顺序,但在某些时候我想删除加载项之一。我该怎么办呢?是否有保存与Python泡菜/ cPickle的一种方式删除或编辑条目?

I basically do sequences of dump and load, but at some point I want to delete one of the loaded entries. How can I do that? Is there a way to remove, or edit entries saved with Python pickle/cpickle?

编辑:在二进制文件中的数据保存咸菜

The data is saved with pickle in a binary file.

推荐答案

要从您的的二进制文件删除腌制对象必须的重写整个文件。
酱菜模块不处理在流任意部分的修改,所以做你想要什么的没有内置的方式。

To delete a pickled object from a binary file you must rewrite the whole file. The pickle module doesn't deal with modifications at arbitrary portions of the stream, so there is no built-in way of doing what you want.

大概是二进制文件的最简单的办法是使用 搁置 模块。

Probably the simplest alternative to binary files is to use the shelve module.

本模块提供了一个字典类似的界面包含腌渍的数据,因为你可以从示例文档中看到一个数据库:

This module provides a dict like interface to a database containing the pickled data, as you can see from the example in the documentation:

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 ,根据不同的平台和库可用。

The database used is ndbm or gdbm, depending on the platform and the libraries available.

请注意:这个作品好,如果数据没有移动到其他平台。如果您希望能够将数据库复制到另一台计算机,然后搁置不会成功的,因为它没有提供关于该库将用于保证。在这种情况下,使用一个明确的SQL数据库可能是最好的选择。

Note: this works well if the data is not moved to an other platform. If you want to be able to copy the database to an other computer then shelve wont work well, since it does not provide guarantees regarding which library will be used. In this case using an explicit SQL database is probably the best option.

这篇关于删除或编辑条目保存泡菜的Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆