联系人管理系统代码
时间: 2023-08-06 18:19:02 浏览: 29
这里我提供一个 Python 实现的联系人管理系统代码,实现了添加、删除、修改、查找和显示联系人等基本操作,同时也实现了数据持久化功能,将联系人信息保存在本地文件中。请注意,这只是一个简单的实现,可能还有很多可以优化的地方。
```python
import os
class Contact:
def __init__(self, name, phone, email):
self.name = name
self.phone = phone
self.email = email
class ContactList:
def __init__(self):
self.contacts = []
def add_contact(self, contact):
self.contacts.append(contact)
def remove_contact(self, name):
for contact in self.contacts:
if contact.name == name:
self.contacts.remove(contact)
return True
return False
def modify_contact(self, name, phone, email):
for contact in self.contacts:
if contact.name == name:
contact.phone = phone
contact.email = email
return True
return False
def search_contact(self, name):
for contact in self.contacts:
if contact.name == name:
return contact
return None
def display_contacts(self):
for contact in self.contacts:
print("Name:", contact.name)
print("Phone:", contact.phone)
print("Email:", contact.email)
print("")
def save_to_file(self, filename):
with open(filename, "w") as f:
for contact in self.contacts:
f.write(contact.name + "," + contact.phone + "," + contact.email + "\n")
def load_from_file(self, filename):
if not os.path.isfile(filename):
return
with open(filename, "r") as f:
for line in f:
fields = line.strip().split(",")
if len(fields) == 3:
name, phone, email = fields
self.add_contact(Contact(name, phone, email))
def main():
filename = "contacts.txt"
contacts = ContactList()
contacts.load_from_file(filename)
while True:
print("Contact List")
print("1. Add contact")
print("2. Remove contact")
print("3. Modify contact")
print("4. Search contact")
print("5. Display all contacts")
print("6. Quit")
choice = int(input("Enter your choice (1-6): "))
print("")
if choice == 1:
name = input("Enter name: ")
phone = input("Enter phone: ")
email = input("Enter email: ")
contacts.add_contact(Contact(name, phone, email))
print("Contact added.")
print("")
elif choice == 2:
name = input("Enter name: ")
if contacts.remove_contact(name):
print("Contact removed.")
else:
print("Contact not found.")
print("")
elif choice == 3:
name = input("Enter name: ")
phone = input("Enter phone: ")
email = input("Enter email: ")
if contacts.modify_contact(name, phone, email):
print("Contact modified.")
else:
print("Contact not found.")
print("")
elif choice == 4:
name = input("Enter name: ")
contact = contacts.search_contact(name)
if contact:
print("Name:", contact.name)
print("Phone:", contact.phone)
print("Email:", contact.email)
print("")
else:
print("Contact not found.")
print("")
elif choice == 5:
contacts.display_contacts()
elif choice == 6:
contacts.save_to_file(filename)
break
else:
print("Invalid choice.")
print("")
if __name__ == "__main__":
main()
```
这个代码中,`Contact` 类表示一个联系人,包含了姓名、电话、邮箱等信息;`ContactList` 类表示联系人列表,包含了添加、删除、修改、查找和显示联系人等基本操作,同时也包含了将联系人信息保存到文件和从文件读取联系人信息的方法。在 `main` 函数中,我们通过一个循环来不停地接收用户输入,并调用 `ContactList` 类的相关方法来实现相应的操作。在退出程序时,我们还将联系人信息保存到本地文件中。