一个很好的通讯本小程序

本文介绍了使用Python编写的一个简单的联系人管理程序,包括创建PersonInformation类来存储联系人信息,ContactList类实现添加、删除、查找、修改和显示联系人功能,以及与CSV文件的读写操作。
摘要由CSDN通过智能技术生成
import os , csv


class PersonInformation:
    def __init__(self , name , gender , age , telephone , address):
        self.name = name
        self.gender = gender
        self.age = age
        self.telephone = telephone
        self.address = address

    def __str__(self):
        return f"名字: {self.name}, 性别: {self.gender}, 年龄: {self.age}, 电话: {self.telephone}, 住址: {self.address}"


class ContactList:
    def __init__(self):
        self.arr = []

    def add_contact(self , person):
        self.arr.append(person)
        self.save_contacts()

    def is_empty(self):
        if not self.arr:
            print("当前联系人列表为空!")

    def remove_contact(self , name):
        person = self.find_contact(name)
        
        if person:
            self.arr.remove(person)
            self.save_contacts()
            print("删除成功!")
            self.is_empty()
        else:
            print("此联系人不存在!")

    def show_contacts(self):
        print('通讯录:')
        for person in self.arr:
            print(person)
        self.is_empty()

    def find_contact(self , name):
        for person in self.arr:
            if person.name == name:
                return person
        return None

    def modify_contact(self , old_name , new_info):
        person = self.find_contact(old_name)
        if person:
            person.name = new_info.name
            person.gender = new_info.gender
            person.age = new_info.age
            person.telephone = new_info.telephone
            person.address = new_info.address
            self.save_contacts()
            print("修改成功!\n " , person)
        else:
            print("此联系人不存在!")

    def save_contacts(self , filename="contacts.csv"):
        with open(filename , 'w' , newline='' , encoding='utf-8') as f:
            writer = csv.writer(f)
            writer.writerow(['姓名' , '性别' , '年龄' , '电话' , '住址'])
            for person in self.arr:
                writer.writerow([person.name , person.gender , person.age , person.telephone , person.address])

    def load_contacts(self , filename="contacts.csv"):
        if not os.path.isfile(filename):
            with open(filename , 'w' , newline='' , encoding='utf-8') as f:
                writer = csv.writer(f)
                writer.writerow(['姓名' , '性别' , '年龄' , '电话' , '住址'])
        with open(filename , 'r' , newline='' , encoding='utf-8') as f:
            reader = csv.reader(f)
            next(reader)
            for row in reader:
                if len(row) == 5:
                    name , gender , age , telephone , address = row
                    self.add_contact(PersonInformation(name , gender , age , telephone , address))
                else:
                    print(f"跳过不完整的联系人记录: {row}")


def menu(contact_list):
    print()
    print("*********************************")
    print("** 1、增加联系人 2、删除联系人 **")
    print("** 3、查找联系人 4、修改联系人 **")
    print("** 5、展示联系人 0、退出通讯录 **")
    print("*********************************")


def main():
    contact_list = ContactList()
    contact_list.load_contacts()
    while True:
        menu(contact_list)
        name , gender , age , telephone , address = [""] * 5
        input_choice = input("请输入您的选择:")
        if input_choice == '1':
            while len(name) < 2:
                name = input("请输入您要添加的联系人的姓名:\n")
                if contact_list.find_contact(name):
                    print(f'此姓名[{name}]已存在!')
                    break
                while gender not in ('男' , '女' , '1' , '0'):
                    gender = input("请输入性别(1-男, 0-女):\n")
                    if gender == '1':
                        gender = '男'
                    elif gender == '0':
                        gender = '女'
                while not age.isnumeric():
                    age = input("请输入年龄:\n")
                while telephone is None or len(telephone) != 11 or not telephone.startswith('1'):
                    telephone = input("请输入手机号:\n")
                while len(address) < 6:
                    address = input("请输入住址(字数不少于6):\n")
                contact_list.add_contact(PersonInformation(name , gender , age , telephone , address))
                print("联系人添加成功!")
        elif input_choice == '2':
            name = input("请输入您要删除的联系人的名字:\n")
            contact_list.remove_contact(name)
        elif input_choice == '3':
            name = input("请输入您要查找的联系人的名字:\n")
            person = contact_list.find_contact(name)
            print(person if person else "此联系人不存在!")
        elif input_choice == '4':
            old_name = input("请输入您要修改的联系人的名字:\n")
            new_info = PersonInformation(*([""] * 5))
            person = contact_list.find_contact(old_name)
            if person:
                print('待修改联系人:(直接回车保留原字段)\n ' , person)
                while len(new_info.name) < 2:
                    new_info.name = input("请输入新的名字:\n")
                    if new_info.name == "":
                        new_info.name = person.name
                    elif contact_list.find_contact(name):
                        print(f'此姓名[{name}]已存在,退出修改!')
                        break
                    while new_info.gender not in ('男' , '女' , '1' , '0'):
                        new_info.gender = input("请输入性别(1-男, 0-女):\n")
                        if new_info.gender == '1':
                            new_info.gender = '男'
                        elif new_info.gender == '0':
                            new_info.gender = '女'
                        elif new_info.gender == "":
                            new_info.gender = person.gender
                    while not new_info.age.isnumeric():
                        new_info.age = input("请输入年龄:\n")
                        if new_info.age == "": new_info.age = person.age
                    while len(new_info.telephone) != 11 or not new_info.telephone.startswith('1'):
                        new_info.telephone = input("请输入新的手机号:\n")
                        if new_info.telephone == "": new_info.telephone = person.telephone
                    while len(new_info.address) < 6:
                        new_info.address = input("请输入新的住址(字数不少于6):\n")
                        if new_info.address == "": new_info.address = person.address
                contact_list.modify_contact(old_name , new_info)
        elif input_choice == '5':
            contact_list.show_contacts()
        elif input_choice == '0':
            print("成功退出通讯录!")
            break
        else:
            print("输入错误,请重新选择!")


if __name__ == "__main__":
    main()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值