python - 无法将数据保存在搁置模块 Python 中
问题描述
我想创建一个 python 文件,当用户输入一个值时,它将保存到字典并更新由 shelve 模块创建的二进制文件。问题是当我再次运行 python 文件时,字典没有更新。没有错误代码或任何东西,我不知道该怎么办。
import shelve
menubook = shelve.open('menu_data', writeback=True)
menubookA = {'main':'toast', 'sub':'egg', 'drink':'milk'}
print(menubookA)
print(menubookA['drink'])
key = input("Enter key: ")
value = input("Enter value: ")
menubookA[key] = value
print(menubookA) # When I check the dictionary here, it has been updated but when I run the program again, the value and key added are gone.
menubook.close()
如果有人可以帮助我,我将不胜感激。
解决方案
您显然忘记将数据写回文件:
import shelve
menubook = shelve.open("menu_data", writeback=True)
# Read data from the file
for key, value in menubook.items():
print("Key: %s = %s" % (key, value))
menubookA = {"main": "toast", "sub": "egg", "drink": "milk"}
print(menubookA)
print(menubookA["drink"])
key = input("Enter key: ")
value = input("Enter value: ")
menubookA[key] = value
print(menubookA) # When I check the dictionary here, it has been updated but when I run the program again, the value and key added are gone.
# Write data back to the file
menubook.update(menubookA)
menubook.close()
推荐阅读
- html - 更改导航栏文本颜色
- r - R如何创建一个新变量,该变量引用另一个数据框中的特定值
- algorithm - AC-3算法的时间复杂度
- sql-server - 无法将大型数据库附加到在 docker 容器进程中运行的 SQL Server 引擎
- python - 将 wordpress xml 文件导入 Python 项目
- svelte - 尝试在 svelte 组件运行之前加载 js 文件
- docker - 如何为 2 个不同的项目配置 nginx(2 个不同的 docker compose 文件)
- date - 月份编号到月份名称
- youtube-iframe-api - 如何格式化多参数 YouTube URL?
- c# - 使用内部编译器和使用 Microsoft.CodeAnalysis.CSharp.Scripting 编译时如何引用外部项目 DLL;