How could I save data after closing my program?

我的未来我决定 提交于 2019-12-03 22:46:26

问题


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

Edit: 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

回答1:


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



回答2:


You can use the Pickle module :

 import pickle

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

Or :

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



回答3:


Pickle works but there are some potential security risks with reading in pickled objects.

Another useful technique is creating a phonebook.ini file and processing it with python's configparser. This gives you the ability to edit the ini file in a text editor and add entries easily.

** I'm using Python 3's new f strings in this solution and I renamed "Information" to "phonebook" to adhere to standard variable naming conventions

You would want to add some error handling for a robust solution but this illistrates the point for you:

import configparser

INI_FN = 'phonebook.ini'


def ini_file_create(phonebook):
    ''' Create and populate the program's .ini file'''
    with open(INI_FN, 'w') as f:
        # write useful readable info at the top of the ini file
        f.write(f'# This INI file saves phonebook entries\n')
        f.write(f'# New numbers can be added under [PHONEBOOK]\n#\n')
        f.write(f'# ONLY EDIT WITH "Notepad" SINCE THIS IS A RAW TEXT FILE!\n\n\n')
        f.write(f"# Maps the name to a phone number\n")
        f.write(f'[PHONEBOOK]\n')
        # save all the phonebook entries
        for entry, number in phonebook.items():
            f.write(f'{entry} = {number}\n')
        f.close()


def ini_file_read():
    ''' Read the saved phonebook from INI_FN .ini file'''
    # process the ini file and setup all mappings for parsing the bank CSV file
    config = configparser.ConfigParser()
    config.read(INI_FN)
    phonebook = dict()
    for entry in config['PHONEBOOK']:
        phonebook[entry] = config['PHONEBOOK'][entry]
    return phonebook

# populate the phonebook with some example numbers
phonebook = {"Police": 911}
phonebook['Doc'] = 554

# example call to save the phonebook
ini_file_create(phonebook)

# example call to read the previously saved phonebook
phonebook = ini_file_read()

Here is the contents of phonebook.ini file created

# This INI file saves phonebook entries
# New numbers can be added under [PHONEBOOK]
#
# ONLY EDIT WITH "Notepad" SINCE THIS IS A RAW TEXT FILE!


# Maps the name to a phone number
[PHONEBOOK]
Police = 911
Doc = 554


来源:https://stackoverflow.com/questions/28661860/how-could-i-save-data-after-closing-my-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!