如何将数据保存到文件而不是字典列表

时间:2015-06-24 16:52:15

标签: python list dictionary

Python 2.7

我创建了一个简单的联系簿应用程序,可以将联系人保存到词典列表中。我希望能够将联系人保存为.csv,.txt文件或类似的东西。我该如何实现?是否有可以实现此目的的Python模块?

# 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()

2 个答案:

答案 0 :(得分:2)

您可以使用Pickle模块写入文件:

import pickle

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

答案 1 :(得分:2)

您可以轻松使用json模块来执行此类操作:

import json

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

其余的取决于你的程序的逻辑。您可以使用

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

和/或设置使用命令行选项,用户选项等读取/写入哪些文件等。