Skip to content Skip to sidebar Skip to footer

How Could I Save Data After Closing My Program?

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 Informatio

Solution 1:

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

Write

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

Read

import ast

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

Solution 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" ) )

Solution 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'defini_file_create(phonebook):
    ''' Create and populate the program's .ini file'''withopen(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 entriesfor entry, number in phonebook.items():
            f.write(f'{entry} = {number}\n')
        f.close()


defini_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 = 911Doc = 554

Post a Comment for "How Could I Save Data After Closing My Program?"