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()
Это звучит, как вы хотите * * сериализации. Для этого есть много модулей Python. Некоторые включают 'pickle' /' shelve' и 'json'. – Brien