Python3第四周作业——员工信息表程

发布时间:2019-09-26 07:31:15编辑:auto阅读(1703)

    员工信息表程序,实现增删改查操作:
    
    可进行模糊查询,语法至少支持下面3种:
      select name,age from staff_table where age > 22
      select  * from staff_table where dept = "IT"
    select  * from staff_table where enroll_date like "2013"
    查到的信息,打印后,最后面还要显示查到的条数
    可创建新员工纪录,以phone做唯一键,staff_id需自增
    可删除指定员工信息纪录,输入员工id,即可删除
    可修改员工信息,语法如下:
      UPDATE staff_table SET dept="Market" where dept = "IT"
    注意:以上需求,要充分使用函数,请尽你的最大限度来减少重复代码

    Python3第四周作业——员工信息表程序
    staff_table (文本文件)

    1 小名 21 13311022222 IT 2013-01-05
    2 小红 23 13311033333 Market 2014-01-05
    3 小童 25 13311044444 Market 2014-01-05
    4 小张 27 13311055555 Market 2015-01-05

    start.py (启动文件)

    import os
    import sys
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    sys.path.append(BASE_DIR)
    import conf,core
    from core import main
    main.main()

    main.py (code文件)

    #!/use/bin/env python
    # -*- coding:utf-8 -*-
    # Author:LT
    import os
    BASE_DATA = os.path.dirname(__file__)
    BASE_DIR = os.path.join(BASE_DATA,'staff_table')
    def sql_select():
        '''
        添加数据前检测staff_table是否为空
        :return:
        '''
        with open(BASE_DIR, "r+", encoding="utf-8") as f:
            line = f.read().strip()
        return line
    
    def select(): # 查询员工信息
        '''
        实现三条sql语句的查询方式
        :return:
        '''
        msg = '''
            请输入一下三种查询方式:
          select name,age from staff_table where age > 22
          select  * from staff_table where dept = "IT"
            select  * from staff_table where enroll_date like "2013"
    '''
        print(msg)
        user_choice = input("请输入您要查询的内容,输入b返回首页>>>:").strip()
        user_choice_list = user_choice.split() # 写入列表
        count = 0
        if user_choice == "select name,age from staff_table where age > %s"%user_choice_list[-1]: #判断是那条查询语句
            with open(BASE_DIR, "r", encoding="utf-8") as f:
                for line in f:
                    if line =="\n": # 跳过文本中最后一行空格
                        continue
                    if line.split()[2] > user_choice_list[-1]: #判断数据库中大于用户输入的age
                        count =count+1 # 获取到的结果计数
                        print(line.split()[1],line.split()[2])
                print("您查到了",count,"条记录")
                return select()
        elif user_choice == "select  * from staff_table where dept = %s" %user_choice_list[-1]:
            with open(BASE_DIR, "r", encoding="utf-8") as f:
                for line in f:
                    if line =="\n":
                        continue
                    if line.split()[4] == user_choice_list[-1].split('"')[1]:
                        count = count + 1
                        print(line.strip())
                print("您查到了", count, "条记录")
                return select()
        elif user_choice == "select  * from staff_table where enroll_date like %s" %user_choice_list[-1]:
            with open(BASE_DIR, "r", encoding="utf-8") as f:
                for line in f:
                    if line =="\n":
                        continue
                    # 判断文本中的时间和用户查找的是否相等,相等输出结果
                    if line.split()[5].split("-")[0] == user_choice_list[-1].split('"')[1].split("-")[0]:
                        count = count + 1
                        print(line.strip())
                print("您查到了", count, "条记录")
                return select()
        elif user_choice == "b" or user_choice =="B":
            return main()
        else:
            print("请输入正确的查询命令")
            return select()
    def update(): # 修改员工信息
        '''
        修改部门名称
        :return:
        '''
        msg = '''
        请输入一下命令修改部门名称:
        UPDATE staff_table SET dept="Market" where dept = "IT"
        '''
        print(msg)
        user_choice = input("请输入修改命令,按b返回首页>>>:").strip()
        if user_choice == "b" or user_choice =="B":
            return main()
        new_dept = user_choice.split("=")[1].split()[0] # 获取第一个等于号后" "的内容(包括"")
        old_dept = user_choice.split("=")[-1] #  获取第二个等于号后" "的内容(包括"")
        if user_choice == "UPDATE staff_table SET dept=%s where dept =%s"%(new_dept,old_dept):
            staff_table_bak = os.path.join(BASE_DATA, 'staff_table_bak')
            with open(BASE_DIR, "r", encoding="utf-8") as f,open(staff_table_bak, "w", encoding="utf-8") as fs:
                for i in f: # 循环staff_table文件内容
                    if i =="\n":
                        continue
                    if old_dept.split('"')[1] in i.split()[4]: # 判断用户输入内容是否在staff_table文件中
                        i=i.replace(old_dept.split('"')[1],new_dept.split('"')[1]) # 修改staff_table文件内容
                    fs.write(i)
                f.close()
                fs.close()
                os.remove(BASE_DIR) # 删除原文件staff_table
                os.rename(staff_table_bak,BASE_DIR) # 新文件改名为staff_table
                print("修改成功")
    def add(): # 添加新员工
        '''
        添加新员工电话唯一用户输入重复的话需要重新输入新员工信息
        :return:
        '''
        name = input("请输入员工姓名:")
        age = input("请输入员工年龄:")
        phone = input("请输入员工电话:")
        dept = input("请输入员工部门:")
        times = input("请输入员工入职时间:")
        with open(BASE_DIR, "r+", encoding="utf-8") as fs:
            lines = fs.readlines()
            if sql_select() == "": # 判断是否有数据没有的话第一条记录ID为1
                user_info = '''
                    1 %s %s %s %s %s
                ''' %(name,age,phone,dept,times)
                userinfo = user_info.strip()
                fs.write(str(userinfo + '\n'))
                print("添加成功")
            else:
                tail = lines[-1].split() # 获取最后一条记录
                staff_id = int(tail[0])+1 # 最后一条记录ID加1,为新的记录ID
                user_info = '''
                    %s %s %s %s %s %s
                ''' %(staff_id,name,age,phone,dept,times)
                for i in lines:
                    if phone in i.split()[3]: # 判断手机号是否存在
                        print("此手机号已存在,请重新输入员工信息")
                        return add()
                    else:
                        userinfo = user_info.strip()
                        fs.write(str(userinfo + '\n'))
                        print("添加成功")
                        break
    def delete(): # 删除员工
        '''
        输入员工ID删除员工
        :return:
        '''
        print(sql_select())
        user_choice = input("请输入要删除的员工ID,按b返回首页>>>:").strip()
        if user_choice == "b" or user_choice =="B":
            return main()
        staff_table_bak = os.path.join(BASE_DATA, 'staff_table_bak')
        with open(BASE_DIR, "r", encoding="utf-8") as f, open(staff_table_bak, "w", encoding="utf-8") as fs:
            for line in f:
                if user_choice in line.split()[0]:
                    continue
                fs.write(line)
            f.close()
            fs.close()
            os.remove(BASE_DIR)
            os.rename(staff_table_bak,BASE_DIR)
            print("删除成功")
    def main():
        while True:
            user_chioce = '''
            1.查询员工信息
            2.修改员工信息
            3.添加新员工
            4.删除员工
            5.退出
            '''
            print(user_chioce)
            user_choice = input("请输入你的选择:")
            if user_choice.isdigit():  # 判断输入的是否数字类型
                if user_choice == '1':
                    select()  # 查询
                elif user_choice == '2':
                    update()  # 修改
                elif user_choice == '3':
                    add()  # 添加
                elif user_choice == '4':
                    delete()  # 删除
                elif user_choice == '5':
                    exit("再见")  # 退出
                else:
                    print("请输入正确的选项")
            else:
                print("请输入正确的选项")

关键字