Mar*_* ER 5 python dictionary pickle klepto
好的,所以我的问题非常具体,我提前道歉。我是一名新程序员,并尝试从头开始自己开发。这是相对成功的,只有我有最后一个问题,我可以看到。您可以在此处完整查看我的代码。
所以我遇到的问题与我保存文件的方式有关。我首先尝试腌制它,因为它是一本字典,但我一直收到错误,因为我的字典是
(name, class) 对。
我在这里搜索,发现我可以尝试使用 JSON 来做同样的事情。以同样的错误结束。最终我找到了有效的 klepto 模块。我成功保存了我的字典并成功加载了它。直到后来我才发现我可以向文件添加新项目,但是每当我从字典中删除某些内容并保存时。下次我加载它。我取下的钥匙还在。
TLDR:可以将内容添加到我的 dict 中并保存到 txt 文件,但是当我从 dict 中删除并保存时,它不会保存已删除的密钥。
无论如何,我很难确定我的问题出在我保存文件的方式或加载文件的方式上,还是两者兼而有之?任何帮助将不胜感激。
编辑:好的,我假设这是我当前设置的保存和加载方式。
try:
alcohols = file_archive('Alcohols.txt')
alcohols.load()
except IOError:
alcohols = {}
print('alcohols doesn\'t exist.')
Run Code Online (Sandbox Code Playgroud)
和
print('Exiting and saving the data.')
alcohols.dump('Alcohols.txt') #saves the dictionary data as is
Run Code Online (Sandbox Code Playgroud)
它在添加新项目时可以很好地保存字典,但说我必须进行编辑并删除某些内容然后保存并退出。下次加载时,它将包含旧项目以及任何新项目。奇怪的是,我似乎在我的所有编辑中都破坏了一些东西。不保存新条目。
编辑2:
del alcohols[name] #deletes the key out of the dict
Run Code Online (Sandbox Code Playgroud)
这就是我删除密钥的方式。最初我使用的是 pop 方法,但是当它无法保存更改时,我尝试了此方法。请注意,它确实从字典中删除了它们的键、值,但保存和重新加载不会反映这种变化。
alcohols[name] = Alcohol() #instantiates the new class
Run Code Online (Sandbox Code Playgroud)
这就是我创建新键值对的方式。
已解决编辑:
我的问题是我从字典中删除它们的方式。以防万一有人后来偶然发现这里。看看@Mike Mckerns 的回答。不得不从存档的字典中删除。
基本上,您是从“内存中”缓存中删除,而不是从“文件”缓存中删除。一个klepto默认归档给你“内存”缓存,您可以直接使用通过字典接口,并且它也给你一个archive是后端。
因此,当您dump将内存中的项目传输到后端时。要从缓存和存档中删除,您必须从两者中删除。
>>> from klepto.archives import *
>>> arch = file_archive('foo.txt')
>>> arch['a'] = 1
>>> arch['b'] = 2
>>> # look at the "in-memory" copy
>>> arch
file_archive('foo.txt', {'a': 1, 'b': 2}, cached=True)
>>> # look at the "on-disk" copy
>>> arch.archive
file_archive('foo.txt', {}, cached=False)
>>> # dump from memory to the file
>>> arch.dump()
>>> arch.archive
file_archive('foo.txt', {'a': 1, 'b': 2}, cached=False)
>>> arch
file_archive('foo.txt', {'a': 1, 'b': 2}, cached=True)
>>> # delete from the in-memory cache
>>> arch.pop('a')
1
>>> # delete from the on-disk cache
>>> arch.archive.pop('a')
1
>>> arch
file_archive('foo.txt', {'b': 2}, cached=True)
>>> arch.archive
file_archive('foo.txt', {'b': 2}, cached=False)
Run Code Online (Sandbox Code Playgroud)
我想我可以更轻松地在单个函数调用中从两者中删除...
| 归档时间: |
|
| 查看次数: |
4371 次 |
| 最近记录: |