Python 如何将数据保存到文件而不是字典列表
Python 2.7 我创建了一个简单的通讯录应用程序,可以将联系人保存到字典列表中。我希望能够将联系人保存到.csv、.txt文件或类似文件中。我如何实现这一点?是否有一个Python模块可以实现这一点Python 如何将数据保存到文件而不是字典列表,python,list,dictionary,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 contac
# 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()
您可以使用
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'))
您可以使用
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'))
您可以很容易地使用模块来完成这类工作:
import json
json.dump(contacts, open('contacts.json', 'w'))
其余部分取决于程序的逻辑。你可以用
try:
contacts = json.load(open('contacts.json', 'r'))
except:
contacts = collections.OrderedDict()
和/或使用命令行选项、用户选项等设置要读取/写入的文件。您可以轻松使用该模块完成这类工作:
import json
json.dump(contacts, open('contacts.json', 'w'))
其余部分取决于程序的逻辑。你可以用
try:
contacts = json.load(open('contacts.json', 'r'))
except:
contacts = collections.OrderedDict()
和/或使用命令行选项、用户选项等设置读取/写入哪些文件。听起来您想要序列化。有许多Python模块可以实现这一点。其中包括
pickle
/shelve
和json
。听起来你想要序列化。有许多Python模块可以实现这一点。其中包括pickle
/shelve
和json
。这不是唯一的序列化吗?尽管python的序列化几乎是人类可读的,但它仍然包含python在反序列化中使用的内容。我想OP需要一个纯人类可读的文件(如csv、txt),谢谢,@ylun.ca-已经将其更改为使用。很好!这比我的解决方案干净得多。不过,Thankstill给了你一票——感谢你的评论。这样做会让网站变得更好。当我添加联系人,然后列出联系人,退出程序,然后再次运行程序并添加另一个联系人时,上一个联系人会被覆盖,这不是唯一的序列化吗?尽管python的序列化几乎是人类可读的,但它仍然包含python在反序列化中使用的内容。我想OP需要一个纯人类可读的文件(如csv、txt),谢谢,@ylun.ca-已经将其更改为使用。很好!这比我的解决方案干净得多。不过,Thankstill给了你一票——感谢你的评论。当我添加联系人,然后列出联系人,退出程序,然后再次运行程序并添加另一个联系人时,以前的联系人会被覆盖