文件的增删改查

时间:2022-10-20 22:08:42

有以下员工信息表

文件的增删改查

当然此表你在文件存储时可以这样表示

1 1,Alex Li,22,13651054608,IT,2013-04-01

现需要对这个员工信息文件,实现增删改查操作

  1. 可进行模糊查询,语法至少支持下面3种:
    1.   select name,age from staff_table where age > 22
    2.   select  * from staff_table where dept = "IT"
    3.       select  * from staff_table where enroll_date like "2013"
    4. 查到的信息,打印后,最后面还要显示查到的条数 
  2. 可创建新员工纪录,以phone做唯一键,staff_id需自增
  3. 可删除指定员工信息纪录,输入员工id,即可删除
  4. 可修改员工信息,语法如下:
    1.   UPDATE staff_table SET dept="Market" WHERE where dept = "IT"

 注意:以上需求,要充分使用函数,请尽你的最大限度来减少重复代码!

aaa.txt

1,Alex Li,22,13651054608,IT,2013-04-01
2,Jack Wang,30,13304320533,HR,2015-05-03
3,Rain Liu,25,1383235322,Sales,2016-04-22
4,Mack Cao,40,1356145343,HR,2009-03-01
import os
def select(data):
    """
    查询语法一: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"
    """
    data1 = data.split()
    if data == ('select name,age from staff_table where age > %s' %(data1[7])):
        with open("aaa.txt", encoding="utf-8") as f:
            list = []
            for line in f:
                i = line.strip().split(",")
                a = i[1]
                b = i[2]
                c = [a, b]
                if b > data1[7]:
                    list.append(c)
            for i in list:
                print(','.join(i))
            print("查询到%s条符合的信息" %len(list))
    elif data == ('select * from staff_table where dept = %s' %(data1[7])):
        with open("aaa.txt", encoding="utf-8") as f2:
            list2 = []
            for line in f2:
                i = line.strip().split(",")
                if data1[7]==i[4]:
                    list2.append(i)
            for i in list2:
                print(','.join(i))
            print("查询到%s条符合的信息" %len(list2))
    elif data == ('select  * from staff_table where enroll_date like %s' % (data1[8])):
        with open("aaa.txt", encoding="utf-8") as f3:
            list3 = []
            for line in f3:
                i = line.strip().split(",")
                if data1[8].strip('""') == i[5][:4]:
                    list3.append(i)
            for i in list3:
                print(','.join(i))
            print("查询到%s条符合的信息" %len(list3))
def add(data):
     """
     添加语法: name,age,phone,dept,enroll-date
     (例如:张,22,123456789,IT,2017-06-18)
     """
     data1 = data.split(",")
     with open("aaa.txt",encoding="utf-8")as f:
         list = []
         phone_list = []
         for line in f:
             i = line.strip().split(",")
             phone_list.append(i[3])
         if data1[2] in phone_list:
            print("phone已存在")
         else:
             with open("aaa.txt", "r+", encoding="utf-8")as f:
                 for line in f:
                     i = line.strip().split(",")
                     # print(i)
                     list.append(i)
                 w = str(int(list[-1][0]) + 1)
                 data1.insert(0, w)
                 data1 = ','.join(data1)
                 f.write('\n'+data1)
                 print(data1+'\n'"添加成功!!!")
def delete(data):
    """
    删除语法:delete from staff_table where staff_id = 12
    """
    data1 = data.split(" ")
    if data == ("delete from staff_table where staff_id = %s" %data1[6]):
        with open("aaa.txt", encoding="utf-8") as f:
            for line in f:
                i = line.strip().split(",")
                if data1[6] == i[0]:
                    i2 = ','.join(i)
                    print(i2)
        with open("aaa.txt", encoding="utf-8")as f_read,open("aaa_back.txt", "a+", encoding="utf-8")as f_write:
            for i in f_read:
                if i2 in i:
                    i = i.replace(i2, "").strip()
                f_write.write(i)
                # f_write.flush()
        os.remove("aaa.txt")
        os.rename("aaa_back.txt","aaa.txt")
        print("删除成功!!!")
def change(data):
    """
    修改语法:UPDATE staff_table SET dept="Market" WHERE where dept = "IT"
    """
    data1 = data.split()
    with open("aaa.txt", encoding="utf-8") as f_read,open("aaa_back.txt","w",encoding="utf-8")as f_write:
        for line in f_read:
            if  data1[3][6:-1] in line:
                line = line.replace(data1[3][6:-1],data1[8][1:-1])
            f_write.write(line)
            # f_write.flush()
    os.remove("aaa.txt")
    os.rename("aaa_back.txt","aaa.txt")
    print("修改成功!!!")
if __name__ == "__main__":
    msg = """
    1:查询
    2:添加
    3:删除
    4:修改
    5:退出
    """
    msg_dict = {
     "1": select,
     "2": add,
     "3": delete,
     "4": change,
     "5": exit,
    }
    while True:
        print('员工信息文件的增删改查:\n'+msg)
        choice = input("输入编号>>:").strip()
        if len(choice) == 0 or choice not in msg_dict: continue
        if choice =='5':break
        else:
            print(msg_dict[choice].__doc__)
        data = input("请输入语法或返回上一级(b):").strip()
        if len(data) == 0:continue
        elif data.lower()=='b':
            continue
        msg_dict[choice](data)