首页 > 解决方案 > 无法将数据保存在搁置模块 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()

如果有人可以帮助我,我将不胜感激。

标签: python

解决方案


您显然忘记将数据写回文件:

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()

推荐阅读