How could I save data after closing my program?

后端 未结 3 782
无人共我
无人共我 2021-01-07 07:52

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 In

3条回答
  •  孤城傲影
    2021-01-07 08:52

    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
    

提交回复
热议问题