1

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
Beta_Penguin
  • 63
  • 1
  • 2
  • 10
  • Does this answer your question? [How do I save my object persistently with Python?](https://stackoverflow.com/questions/4529815/how-do-i-save-my-object-persistently-with-python) – mkrieger1 Jul 15 '22 at 12:49

3 Answers3

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" ) )
Alexander
  • 12,424
  • 5
  • 59
  • 76
2

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())
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
1

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
Scott Hellam
  • 449
  • 5
  • 6