How could I save data after closing my program?

后端 未结 3 784
无人共我
无人共我 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:40

    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())
    
    0 讨论(0)
  • 2021-01-07 08:45

    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" ) )
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题