gpt4 book ai didi

python - 关闭程序后如何保存数据?

转载 作者:行者123 更新时间:2023-11-30 23:14:38 27 4
gpt4 key购买 nike

我目前正在使用字典制作电话簿目录。我不知道关闭程序后有什么方法可以保存信息。我需要保存变量信息,以便稍后添加更多内容并打印它。

    Information={"Police":911}
def NewEntry():
Name=raw_input("What is the targets name?")
Number=raw_input("What is the target's number?")
Number=int(Number)
Information[Name]=Number

NewEntry()
print Information

编辑:我现在正在使用 Pickle 模块,这是我当前的代码,但它不起作用:

     import pickle
Information={"Police":911}
pickle.dump(Information,open("save.p","wb"))
def NewEntry():
Name=raw_input("What is the targets name?")
Number=raw_input("What is the target's number?")
Number=int(Number)
Information[Name]=Number
Information=pickle.load(open("save.p","rb"))
NewEntry()
pickle.dump(Information,open("save.p","wb"))
print Information

最佳答案

您可以使用Pickle模块:

 import pickle

# Save a dictionary into a pickle file.
favorite_color = { "lion": "yellow", "kitty": "red" }
pickle.dump( favorite_color, open( "save.p", "wb" ) )

或者:

 # Load the dictionary back from the pickle file.
favorite_color = pickle.load( open( "save.p", "rb" ) )

关于python - 关闭程序后如何保存数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28661860/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com