关闭程序后如何保存数据? [英] How could I save data after closing my program?

查看:72
本文介绍了关闭程序后如何保存数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用词典处理电话簿目录.关闭程序后,我不知道任何保存信息的方法.我需要保存变量信息,以便以后添加更多内容并打印.

I am currently working on a phone book directory using dictionaries. I didn't know any way to save the information after closing the program. I need to save the variable Information so that I can add more later and print it.

    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模块,这是我当前的代码,但是它不起作用:

I am now using the Pickle module and this is my current code, but it isnt working:

     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

推荐答案

您可以以字符串形式写入文本文件,然后以字典形式读取解析:

You can write to a text file as a string, then read parsing as a dictionary:

Write

with open('info.txt', 'w') as f:
    f.write(str(your_dict))

Read

import ast

with open('info.txt', 'r') as f:
    your_dict = ast.literal_eval(f.read())

这篇关于关闭程序后如何保存数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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