cbandara
cbandara

Reputation: 111

How to save data to file instead of list of dictionaries

Python 2.7

I have created a simple contact book app that saves the contacts into a list of dictionaries. I want to be able to save the contacts into a .csv, .txt file or something similar. How do I implement this? Is there a Python module that can accomplish this?

# Import Collections to use Ordered Dictionary
import collections

# The main class
def main():

    # Creates an empty list of contacts
    contacts = []

    loop = True

    # Create a while loop for the menu that keeps looping for user input until loop = 0
    while loop == True:

        # Prints menu for the user in command line
        print """
        Contact Book App
        a) New Contact
        b) List Contacts
        c) Search Contacts
        d) Delete Contact
        e) Quit
         """

        # Asks for users input from a-e
        userInput = raw_input("Please select an option: ").lower()

        # OPTION 1 : ADD NEW CONTACT
        if userInput == "a":
            contact = collections.OrderedDict()

            contact['name'] = raw_input("Enter name: ")
            contact['phone'] = raw_input("Enter phone: ")
            contact['email'] = raw_input("Enter email: ")

            contacts.append(contact)

            print "Contact Added!"
            # For Debugging Purposes
            # print(contacts)

        # OPTION 2 : LIST ALL CONTACTS
        elif userInput == "b":
            print "Listing Contacts"

            for i in contacts:
                print i
                # Want to display all contacts into a neat table

        # OPTION 3 : SEARCH CONTACTS
        elif userInput == "c":
            print "Searching Contacts"
            search = raw_input("Please enter name: ")
            # Want to be able to search contacts by name, phone number or email

        # OPTION 4 : DELETE A CONTACT
        elif userInput == "d":
            print
            # Want to be able to delete contacts name, phone number or email

        # OPTION 5 : QUIT PROGRAM
        elif userInput == "e":
            print "Quitting Contact Book"
            loop = False
        else:
            print "Invalid Input! Try again."


main()

Upvotes: 1

Views: 373

Answers (2)

Ami Tavory
Ami Tavory

Reputation: 76297

You can easily use the json module to do this sort of stuff:

import json

json.dump(contacts, open('contacts.json', 'w'))

The rest depends on the logic of your program. You could start the code with

try:
    contacts = json.load(open('contacts.json', 'r'))
except:
    contacts = collections.OrderedDict()

and/or set which files are read/written using command line options, user options, etc. etc.

Upvotes: 3

ylun
ylun

Reputation: 2534

You can write to a file using the Pickle module:

import pickle

with open('FILENAME', "a") as f:
    for entry in contacts:
        f.write(contacts[entry]['name'] + ',' + contacts[entry]['phone'] + ',' + contacts[entry]['email'] + '\n'))

Upvotes: 2

Related Questions