员工信息增删改查

内容:

1.修改个人信息程序

2.员工信息增删改查

 

 

 

一、修改个人信息程序

需求:

 1 在一个文件中存入多个人的个人信息,如以下:
 2 username password age position department
 3 alex      abc123  21  Engineer       IT
 4 rain      xyz456  32  Teacher       Teaching
 5 
 6 功能:
 7 1.输入用户名及密码,正确登陆系统后显示
 8 (1)修改个人信息
 9 (2)打印个人信息
10 (3)修改密码
11 2.上述每个选项写一个方法
12 3.登陆输错3次退出程序

实现1:

  1 # 员工信息文件 -> info_employee.txt
  2 
  3 # 员工信息(列表嵌套) -> [ "alex", "abc123", 21, "Engineer", "IT"]
  4 info = []
  5 
  6 
  7 # 获取员工信息
  8 def get_info():
  9     with open("info_employee.txt", 'r', encoding="utf-8") as f:
 10         # 读取每一行的数据存入列表中
 11         details = f.readlines()
 12         # 遍历列表将每一行的数据分开并将一行的数据作为一个列表存入info列表中
 13         for detail in details:
 14             detail = detail.strip().split()
 15             info.append(detail)
 16 
 17 
 18 # 登陆
 19 def login():
 20     users_pwds = []
 21     # 获取用户名及密码:
 22     for index in range(1, len(info)):
 23         # 获取用户数据
 24         detail = info[index]
 25         # 获取用户名及密码
 26         user = detail[0]
 27         pwd = detail[1]
 28         users_pwds.append(dict({user: pwd}))
 29     # 输入用户名及密码并验证用户名及密码是否正确
 30     for i in range(4):
 31         if i == 3:
 32             print("你已经输错3次,不能再登陆了!")
 33             exit()
 34         # 输入用户名及密码
 35 
 36         username, password = input("input the username and password(eg: user pwd): ").strip().split()
 37         for item in users_pwds:
 38             if item.get(username, None) == password:
 39                 print("登陆成功!欢迎%s!" % username)
 40                 now_user = username
 41                 return now_user
 42         else:
 43             print("用户名或密码错误!请重新输入")
 44 
 45 
 46 # 打印选项
 47 def output_chose():
 48     # 打印选项
 49     print("你有如下选项: ")
 50     print("1.修改个人信息")
 51     print("2.打印个人信息")
 52     print("3.修改密码")
 53     print("4.退出系统")
 54     # 用户输入选项,函数返回选项对应的整数
 55     while True:
 56         choice = input("请输入选项(数字): ")
 57         if choice.isdigit():
 58             choice = int(choice)
 59             if 1 <= choice <= 4:
 60                 return choice
 61             else:
 62                 print("请输入正确的数字选项!")
 63         else:
 64             print("请输入正确的数字选项!")
 65             continue
 66 
 67 
 68 # 将修改后的信息写入文件中
 69 def write_info():
 70     with open("info_employee.txt", "w", encoding="utf-8") as f:
 71         for item in info:
 72             for value in item:
 73                 f.write(str(value)+"\t")
 74             f.write("\n")
 75 
 76 
 77 # 1.修改个人信息
 78 def change_info(update_name):
 79     index = 0
 80     for personal in info:
 81         if personal[0] == update_name:
 82             for i in range(len(personal)):
 83                 print(i+1, info[0][i], ": ", personal[i])
 84             choice = int(input("请输入你想要修改的选项: "))
 85             print("修改前的值: ", info[index][choice-1])
 86             change = input("请输入修改后的值: ")
 87             info[index][choice-1] = change
 88             write_info()
 89         index += 1
 90 
 91 
 92 # 2.打印个人信息
 93 def output_info(personal_name):
 94     for personal in info:
 95         if personal[0] == personal_name:
 96             for i in range(len(personal)):
 97                 print(info[0][i], ": ", personal[i])
 98 
 99 
100 # 3.修改密码
101 def change_pwd(change_name):
102     index = 0
103     # 遍历找到用户信息的位置
104     for item in info:
105         if item[0] == change_name:
106             break
107         index += 1
108     # 输入两次密码,一样就通过,否则就重新输入
109     while True:
110         pwd1 = input("请输入新密码: ")
111         pwd2 = input("请再一次输入新密码: ")
112         if pwd1 == pwd2:
113             info[index][1] = pwd1
114             print("密码输入正确,修改密码成功!")
115             write_info()
116             break
117         else:
118             print("两次输入的密码不一样请重新输入!")
119 
120 
121 if __name__ == '__main__':
122     get_info()
123     login_user = login()
124     while True:
125         number = output_chose()
126         if number == 1:
127             change_info(login_user)
128         if number == 2:
129             output_info(login_user)
130         if number == 3:
131             change_pwd(login_user)
132         if number == 4:
133             exit()

实现2:

  1 # __author__ = "wyb"
  2 # date: 2018/4/20
  3 
  4 
  5 def get_info():
  6     """
  7     获取员工信息
  8     :return: 返回列表,列表中每一项是存储员工信息的字典
  9     """
 10     info = []
 11     with open("info_employee.txt", 'r', encoding="utf-8") as f:
 12         # 读取每一行的数据存入列表中
 13         details = f.readlines()
 14         topics = details[0].split()                                                 # 第一排数据作为键
 15         for index in range(1, len(details)):                                        # 第二排开始的数据作为值
 16             detail = details[index].strip().split()
 17             dic = dict(zip(topics, detail))                                         # 把两个列表合并为一个字典
 18             dic["user_id"] = index                                                  # 向用户数据中添加一项user_id方便替换用户数据
 19             info.append(dic)
 20     return info
 21 
 22 
 23 def write_info(user_data):
 24     """
 25     将修改后的用户信息写入文件中
 26     :param user_data: 用户信息
 27     :return:
 28     """
 29     data = get_info()                                               # 获取文件中数据
 30     for index in range(len(data)):                                  # 替换用户数据
 31         if data[index]["user_id"] == user_data["user_id"]:
 32             data[index] = user_data
 33 
 34     with open("info_employee.txt", 'w', encoding="utf-8") as f:     # 将数据写入新文件
 35         f.write("username\tpassword\tage\tposition\tdepartment\n")
 36         for item in data:
 37             f.write("%s\t%s\t%s\t%s\t%s\n" % (item["username"], item["password"], item["age"], item["position"], item["department"]))
 38 
 39     return
 40 
 41 
 42 def login(info):
 43     """
 44     登陆接口
 45     :param info: 个人信息所有数据
 46     :return: 返回状态及信息
 47     """
 48     # 输入用户名及密码并验证用户名及密码是否正确
 49     for i in range(4):
 50         if i == 3:
 51             return {"status": -1, "error": "输错3次,不能再登陆"}
 52         # 输入用户名及密码
 53         username = input("username>>>").strip()
 54         password = input("password>>>").strip()
 55         for item in info:
 56             if item["username"] == username and item["password"] == password:                   # 登陆成功
 57                 return {"status": 0, "msg": "欢迎%s登陆" % username, "username": username}
 58         else:
 59             print("用户名或密码错误!请重新输入")
 60 
 61 
 62 def output_info(user_info):
 63     """
 64     打印个人信息
 65     :param user_info: 某个用户的个人信息
 66     :return:
 67     """
 68     print("USER INFO".center(50, "-"))
 69     for k, v in user_info.items():
 70         print("%18s: %s" % (k, v))
 71     print("END".center(50, "-"))
 72     return
 73 
 74 
 75 def change_info(user_info):
 76     """
 77     修改个人信息
 78     :param user_info: 某个用户的个人信息
 79     :return:
 80     """
 81     print("选择你要修改的个人信息: ")
 82     dic = {}
 83     for index, item in enumerate(user_info.keys()):         # 输出个人信息及选项,并将个人信息和选项捆绑
 84         if item == "user_id":
 85             continue
 86         print("%s: %s" % (index+1, item))
 87         dic[str(index+1)] = item
 88     choice = input("输入选项>>>").strip()
 89     change = input("输入修改后的值>>>").strip()
 90     user_info[dic[str(choice)]] = change                    # 修改信息
 91     write_info(user_info)                                   # 修改后的信息写入文件
 92     return
 93 
 94 
 95 def change_pwd(user_info):
 96     """
 97     修改用户的密码
 98     :param user_info: 某个用户的个人信息
 99     :return:
100     """
101     retry_times = 0                                         # 最多允许尝试3次
102     while True:
103         retry_times += 1
104         pwd = input("输入修改后的密码: ").strip()
105         pwd_again = input("再次输入密码: ").strip()
106         if pwd == pwd_again:
107             user_info["password"] = pwd
108             write_info(user_info)                           # 将修改后的数据写入文件
109             print("两次输入密码相符,修改成功")
110             return
111         else:
112             print("两次密码输入不符,请重新输入密码")
113 
114 
115 def controller(all_info, username):
116     """
117     功能分发器
118     :param all_info: 所有用户信息
119     :param username:  登陆用户的用户名
120     :return:
121     """
122     user_data = {}                          # 登陆用户的个人信息
123     menus = [                               # 功能菜单
124         ("修改个人信息", change_info),
125         ("输出个人信息", output_info),
126         ("修改密码", change_pwd),
127         ("退出系统", 0),
128     ]
129     for item in all_info:                   # 根据用户名找到某个用户的用户信息
130         if item["username"] == username:
131             user_data = item
132     while True:
133         for index, item in enumerate(menus):    # 输出功能菜单
134             print(index + 1, item[0])
135         choice = input("请输入序号选择功能>>>")
136         if choice.isdigit():
137             choice = int(choice)
138             if 1 <= choice < len(menus):
139                 # 调用相应的功能函数
140                 menus[choice-1][1](user_data)
141             elif choice == len(menus):
142                 exit("退出系统")
143         if not choice:
144             continue
145 
146 
147 def entrance():
148     """
149     程序主入口
150     :return:
151     """
152     details = get_info()                # 获取所有数据
153     res = login(details)                # 调用登陆接口    
154     username = ""
155     if res["status"] == 0:              # 成功登陆
156         username = res["username"]      # 获取登陆的用户的用户名
157         print(res["msg"])
158     else:                               # 登陆失败
159         print(res)
160         exit()
161     controller(details, username)       # 调用功能分发器
162 
163 
164 if __name__ == '__main__':
165     entrance()

 

 

 

二、员工信息增删改查

需求:

 

实现:

这个题说白了就算麻烦,用笨办法也可以做出来,以下代码是我个人的实现,不同的人有不同的理解,实现也许有不同

整体思路: 在文件中存储员工信息,一个函数读取所有员工信息,并只在程序启动时读取,输入命令后根据不同命令调用不同函数来处理,如果命令是修改或增加或删除,在执行命令后将修改后的员工信息写入文件中

 

文件结构:

1 1,Alex Li,22,13651054608,IT,2013-04-01
2 2,wyb,20,15698704367,CTO,2016-8-9
3 3,tim,26,18945312218,HR,2015-9-3
4 4,Eric,30,18796342152,IT,2012-4-6
5 5,rachel,32,15367833458,Market,2013-9-3
6 6,jack,22,18398035682,HR,2016-7-6

 

测试命令:

 1 find:
 2     find * from staff_table
 3     find name,age from staff_table
 4     find name,age from staff_table where age > 22
 5     find * from staff_table where dept = "IT"
 6     find * from staff_table where enroll_date like "2013"
 7 
 8 add:
 9     add staff_table Alex Li,25,13651054608,IT,2016-7-8
10     add staff_table Alex Li,25,13444679873,IT,2016-7-8
11     add staff_table woz,20,13594372910,IT,2016-9-1
12 
13 del:
14     del from staff_table where id=3
15     del from staff_table where id=13
16 
17 update:
18     update staff_table set dept = "market" where dept = "IT"
19     update staff_table set age = 25 where name = "Alex Li"

 

输入命令并进行相关处理:

 1 # 根据命令选择相应函数
 2 def chose_command(commands):
 3     command = commands[0]
 4     if command == "find":
 5         find(commands)
 6     if command == "add":
 7         add(commands)
 8     if command == "del":
 9         delete(commands)
10     if command == "update":
11         update(commands)
12 
13 
14 # 输入命令并进行相关处理
15 def input_command():
16     while True:
17         command = input("请输入与增删改查相关命令(q或exit退出程序): ")
18         # 退出程序
19         if command == "exit" or command == "q":
20             exit()
21         # 将字母统一转换成小写
22         order = ""
23         for i in range(len(command)):
24             if command[i].isalpha():
25                 order += command[i].lower()
26             else:
27                 order += command[i]
28         command = order
29         # 分割字符串
30         command = command.split()
31         orders = ["find", "del", "add", "update"]
32         # 确保命令的首个单词正确
33         if command[0] not in orders:
34             print("请输入正确的命令!")
35             continue
36         # 选择命令
37         chose_command(command)

 

查找及修改:

  1 # 输出查找及修改结果
  2 def output_result(res, flag):
  3     print("一共%s了%d条数据" % (flag, len(res)))
  4     if len(res) != 0:
  5         print("%s如下:" % flag)
  6     for s in res:
  7         print(s)
  8 
  9 
 10 def find_condition(rows, choice):
 11     # 存储符合条件的行
 12     res = []
 13     c1, c2, c3 = choice[0], choice[1], choice[2]
 14     # 处理c3
 15     if c3.isdigit():
 16         c3 = int(c3)
 17     else:
 18         c3 = c3.strip("\"")
 19         # print(c3)
 20     if c2 == "=":
 21         for row in rows:
 22             item = str(row[c1])
 23             # 数字
 24             if item.isdigit():
 25                 if int(item) == c3:
 26                     res.append(row)
 27             # 字符串
 28             elif item.lower() == c3:
 29                 res.append(row)
 30     if c2 == ">":
 31         for row in rows:
 32             if row[c1] > c3:
 33                 res.append(row)
 34     if c2 == ">=":
 35         for row in rows:
 36             if row[c1] >= c3:
 37                 res.append(row)
 38     if c2 == "<":
 39         for row in rows:
 40             if row[c1] < c3:
 41                 res.append(row)
 42     if c2 == "<=":
 43         for row in rows:
 44             if row[c1] <= c3:
 45                 res.append(row)
 46     if c2 == "like":
 47         for row in rows:
 48             if c3 in row[c1]:
 49                 res.append(row)
 50     output_result(res, "查找")
 51 
 52 
 53 def find(commands):
 54     # find * from staff_table
 55     # find name,age from staff_table
 56     if len(commands) == 4:
 57         #
 58         column = commands[1]
 59         #
 60         table = commands[3]
 61         models = tables[table]
 62         if column == '*':
 63             output_result(models, "查找")           # 输出结果
 64         else:
 65             res = []                        # 存储选择的列
 66             columns = column.split(',')     # 选择的列
 67             # 提取选择的列
 68             for model in models:
 69                 res_dict = {}
 70                 for item in columns:
 71                     res_dict[item] = model[item]
 72                 res.append(res_dict)
 73             output_result(res, "查找")              # 输出结果
 74     # find name,age from staff_table where age > 22
 75     # find * from staff_table where dept = "IT"
 76     # find * from staff_table where enroll_date like "2013"
 77     elif len(commands) == 8:
 78         column, table = commands[1], commands[3]        # 列名和表名
 79         choice = commands[-3::1]                        # 筛选条件
 80         # print(column, table, chose1, chose2, chose3)
 81         #
 82         models = tables[table]
 83         if column == '*':
 84             find_condition(models, choice)      # 根据条件查找
 85         else:
 86             res = []                            # 存储选择的列
 87             columns = column.split(',')         # 选择的列
 88             # 提取选择的列
 89             for model in models:
 90                 res_dict = {}
 91                 for item in columns:
 92                     res_dict[item] = model[item]
 93                 res.append(res_dict)
 94             find_condition(res, choice)     # 根据条件查找
 95 
 96 def update(commands):
 97     # update staff_table set dept = "market" where dept = "IT"
 98     # update staff_table set age = 25 where name = "Alex Li"
 99     res = []            # 存储修改过的行
100     #
101     table = commands[1]
102     models = tables[table]
103     condition = commands[7::]               # 选择行的条件
104     change = (commands[3], commands[5])     # 要修改的键以及其对应值
105     # 处理条件
106     if condition[0] == "id":
107         print("不能修改id!")
108         return
109     if len(condition) == 3:
110         if condition[2].isdigit():
111             condition[2] = int(condition[2])
112         else:
113             condition[2] = condition[2].strip("\"")
114     if len(condition) == 4:
115         condition[2] = condition[2] + " " + condition[3]
116         condition[2] = condition[2].strip("\"")
117     # print(condition)
118     # 根据条件选择表中的行
119     for index in range(len(models)):
120         dic = models[index][condition[0]]
121         if str(dic).lower() == condition[2]:
122             res.append(models[index])
123     # 修改相应的值
124     for index in range(len(res)):
125         value = change[1]           # 要修改的值
126         if value.isdigit():
127             value = int(value)
128         else:
129             value = value.strip("\"")
130         res[index][change[0]] = value
131     # 输出修改结果
132     output_result(res, "修改")
133     # 将修改结果存入文件中(根据id值将修改后的行赋给表中的行)
134     for i in range(len(models)):
135         for item in res:
136             mid = models[i]["id"]
137             if mid == item["id"]:
138                 models[i] = item
139     write_info(models)

 

删除及增加:

 1 def add(commands):
 2     # add staff_table Alex Li,25,13444679873,IT,2016-7-8
 3     # add staff_table woz,20,13594372910,IT,2016-9-1
 4     #
 5     table = commands[1]
 6     models = tables[table]
 7     # 待添加的员工信息
 8     add_details = commands[2:]
 9     details = []
10     # 处理数据
11     if len(add_details) == 1:
12         details = add_details[0].split(',')
13     if len(add_details) == 2:
14         details = add_details[1].split(',')
15         details[0] = add_details[0] + " " + details[0]
16     # print(models)
17     # print(details[3])
18     # 判断员工信息是否可以添加进表
19     if details[2] not in tels:
20         print("新增一条员工信息")
21     else:
22         print("电话号重复,无法新增员工信息!")
23         return
24     # 获取id值
25     aid = models[-1]["id"] + 1
26     # 将可添加的员工信息加入新字典中
27     new_dict = {}
28     new_dict.update(id=aid, name=details[0], age=int(details[1]), tel=details[2], dept=details[3], enroll_date=details[4])
29     # 将新字典加入表中
30     models.append(new_dict)
31     # 写入数据
32     write_info(models)
33 
34 def delete(commands):
35     # del from staff_table where id=3
36     # del from staff_table where id=13
37     #
38     table = commands[2]
39     models = tables[table]
40     # 选择条件
41     condition = commands[-1]
42     # print(table, condition)     # 表名和条件
43     if "=" in condition:
44         conditions = condition.split('=')
45         # print(conditions)
46         for index in range(len(models)):
47             if models[index]["id"] == int(conditions[1]):
48                 print("删除一条员工信息,删除信息如下:")
49                 print(models[index])
50                 del models[index]
51                 break
52         else:
53             print("请输入正确的del命令!")
54             return
55         write_info(models)
56     else:
57         print("请输入正确的del命令!")
58         return

 

文件读取及写入:

 1 # 表结构: tables -> staff_table -> employee_detail
 2 # 全局变量:
 3 tables = {}
 4 tels = []       # 字符串存储员工的电话号
 5 
 6 
 7 # 获取员工信息
 8 def get_info():
 9     with open("employee_info.txt", 'r', encoding="utf-8") as f:
10         # staff_table存储多行员工信息,每一行的员工信息存在字典中
11         staff_table = []
12         # 读取每一行的数据存入列表中
13         details = f.readlines()
14         # 遍历列表将每一行的数据分开并将一行的数据作为一个字典存入info列表中
15         for detail in details:
16             employee_detail = {}
17             detail = detail.strip()
18             items = detail.split(',')
19             # 去掉开头和结尾的空白
20             for i in range(len(items)):
21                 items[i] = items[i].strip()
22             # 将一条员工信息存入字典
23             employee_detail.update(id=int(items[0]), name=items[1], age=int(items[2]), tel=items[3], dept=items[4], enroll_date=items[5])
24             tels.append(items[3])
25             staff_table.append(employee_detail)
26         tables.update(staff_table=staff_table)
27         # print(tables)
28         # print(tables["staff_table"])
29 
30 
31 # 将员工信息写入文件中
32 def write_info(models):
33     with open("employee_info.txt", "w", encoding="utf-8") as f:
34         for model in models:
35             f.write(str(model["id"]) + "," + model["name"] + "," + str(model["age"]) + ",")
36             f.write(model["tel"] + "," + model["dept"] + "," + model["enroll_date"] + "\n")

 

全部代码:

  1 # __author__ = "wyb"
  2 # date: 2018/4/22
  3 
  4 # 表结构: tables -> staff_table -> employee_detail
  5 tables = {}
  6 tels = []       # 字符串存储员工的电话号
  7 
  8 
  9 # 获取员工信息
 10 def get_info():
 11     with open("employee_info.txt", 'r', encoding="utf-8") as f:
 12         # staff_table存储多行员工信息,每一行的员工信息存在字典中
 13         staff_table = []
 14         # 读取每一行的数据存入列表中
 15         details = f.readlines()
 16         # 遍历列表将每一行的数据分开并将一行的数据作为一个字典存入info列表中
 17         for detail in details:
 18             employee_detail = {}
 19             detail = detail.strip()
 20             items = detail.split(',')
 21             # 去掉开头和结尾的空白
 22             for i in range(len(items)):
 23                 items[i] = items[i].strip()
 24             # 将一条员工信息存入字典
 25             employee_detail.update(id=int(items[0]), name=items[1], age=int(items[2]), tel=items[3], dept=items[4], enroll_date=items[5])
 26             tels.append(items[3])
 27             staff_table.append(employee_detail)
 28         tables.update(staff_table=staff_table)
 29         # print(tables)
 30         # print(tables["staff_table"])
 31 
 32 
 33 # 将员工信息写入文件中
 34 def write_info(models):
 35     with open("employee_info.txt", "w", encoding="utf-8") as f:
 36         for model in models:
 37             f.write(str(model["id"]) + "," + model["name"] + "," + str(model["age"]) + ",")
 38             f.write(model["tel"] + "," + model["dept"] + "," + model["enroll_date"] + "\n")
 39 
 40 
 41 # 输出查询及修改结果
 42 def output_result(res, flag):
 43     print("一共%s了%d条数据" % (flag, len(res)))
 44     if len(res) != 0:
 45         print("%s如下:" % flag)
 46     for s in res:
 47         print(s)
 48 
 49 
 50 def find_condition(rows, choice):
 51     # 存储符合条件的行
 52     res = []
 53     c1, c2, c3 = choice[0], choice[1], choice[2]
 54     # 处理c3
 55     if c3.isdigit():
 56         c3 = int(c3)
 57     else:
 58         c3 = c3.strip("\"")
 59         # print(c3)
 60     if c2 == "=":
 61         for row in rows:
 62             item = str(row[c1])
 63             # 数字
 64             if item.isdigit():
 65                 if int(item) == c3:
 66                     res.append(row)
 67             # 字符串
 68             elif item.lower() == c3:
 69                 res.append(row)
 70     if c2 == ">":
 71         for row in rows:
 72             if row[c1] > c3:
 73                 res.append(row)
 74     if c2 == ">=":
 75         for row in rows:
 76             if row[c1] >= c3:
 77                 res.append(row)
 78     if c2 == "<":
 79         for row in rows:
 80             if row[c1] < c3:
 81                 res.append(row)
 82     if c2 == "<=":
 83         for row in rows:
 84             if row[c1] <= c3:
 85                 res.append(row)
 86     if c2 == "like":
 87         for row in rows:
 88             if c3 in row[c1]:
 89                 res.append(row)
 90     output_result(res, "查找")
 91 
 92 
 93 def find(commands):
 94     # find * from staff_table
 95     # find name,age from staff_table
 96     if len(commands) == 4:
 97         #
 98         column = commands[1]
 99         #
100         table = commands[3]
101         models = tables[table]
102         if column == '*':
103             output_result(models, "查找")           # 输出结果
104         else:
105             res = []                        # 存储选择的列
106             columns = column.split(',')     # 选择的列
107             # 提取选择的列
108             for model in models:
109                 res_dict = {}
110                 for item in columns:
111                     res_dict[item] = model[item]
112                 res.append(res_dict)
113             output_result(res, "查找")              # 输出结果
114     # find name,age from staff_table where age > 22
115     # find * from staff_table where dept = "IT"
116     # find * from staff_table where enroll_date like "2013"
117     elif len(commands) == 8:
118         column, table = commands[1], commands[3]        # 列名和表名
119         choice = commands[-3::1]                        # 筛选条件
120         # print(column, table, chose1, chose2, chose3)
121         #
122         models = tables[table]
123         if column == '*':
124             find_condition(models, choice)      # 根据条件查找
125         else:
126             res = []                            # 存储选择的列
127             columns = column.split(',')         # 选择的列
128             # 提取选择的列
129             for model in models:
130                 res_dict = {}
131                 for item in columns:
132                     res_dict[item] = model[item]
133                 res.append(res_dict)
134             find_condition(res, choice)     # 根据条件查找
135 
136 
137 def add(commands):
138     # add staff_table Alex Li,25,13444679873,IT,2016-7-8
139     # add staff_table woz,20,13594372910,IT,2016-9-1
140     #
141     table = commands[1]
142     models = tables[table]
143     # 待添加的员工信息
144     add_details = commands[2:]
145     details = []
146     # 处理数据
147     if len(add_details) == 1:
148         details = add_details[0].split(',')
149     if len(add_details) == 2:
150         details = add_details[1].split(',')
151         details[0] = add_details[0] + " " + details[0]
152     # print(models)
153     # print(details[3])
154     # 判断员工信息是否可以添加进表
155     if details[2] not in tels:
156         print("新增一条员工信息")
157     else:
158         print("电话号重复,无法新增员工信息!")
159         return
160     # 获取id值
161     aid = models[-1]["id"] + 1
162     # 将可添加的员工信息加入新字典中
163     new_dict = {}
164     new_dict.update(id=aid, name=details[0], age=int(details[1]), tel=details[2], dept=details[3], enroll_date=details[4])
165     # 将新字典加入表中
166     models.append(new_dict)
167     # 写入数据
168     write_info(models)
169 
170 
171 def delete(commands):
172     # del from staff_table where id=3
173     # del from staff_table where id=13
174     #
175     table = commands[2]
176     models = tables[table]
177     # 选择条件
178     condition = commands[-1]
179     # print(table, condition)     # 表名和条件
180     if "=" in condition:
181         conditions = condition.split('=')
182         # print(conditions)
183         for index in range(len(models)):
184             if models[index]["id"] == int(conditions[1]):
185                 print("删除一条员工信息,删除信息如下:")
186                 print(models[index])
187                 del models[index]
188                 break
189         else:
190             print("请输入正确的del命令!")
191             return
192         write_info(models)
193     else:
194         print("请输入正确的del命令!")
195         return
196 
197 
198 def update(commands):
199     # update staff_table set dept = "market" where dept = "IT"
200     # update staff_table set age = 25 where name = "Alex Li"
201     res = []            # 存储修改过的行
202     #
203     table = commands[1]
204     models = tables[table]
205     condition = commands[7::]               # 选择行的条件
206     change = (commands[3], commands[5])     # 要修改的键以及其对应值
207     # 处理条件
208     if condition[0] == "id":
209         print("不能修改id!")
210         return
211     if len(condition) == 3:
212         if condition[2].isdigit():
213             condition[2] = int(condition[2])
214         else:
215             condition[2] = condition[2].strip("\"")
216     if len(condition) == 4:
217         condition[2] = condition[2] + " " + condition[3]
218         condition[2] = condition[2].strip("\"")
219     # print(condition)
220     # 根据条件选择表中的行
221     for index in range(len(models)):
222         dic = models[index][condition[0]]
223         if str(dic).lower() == condition[2]:
224             res.append(models[index])
225     # 修改相应的值
226     for index in range(len(res)):
227         value = change[1]           # 要修改的值
228         if value.isdigit():
229             value = int(value)
230         else:
231             value = value.strip("\"")
232         res[index][change[0]] = value
233     # 输出修改结果
234     output_result(res, "修改")
235     # 将修改结果存入文件中(根据id值将修改后的行赋给表中的行)
236     for i in range(len(models)):
237         for item in res:
238             mid = models[i]["id"]
239             if mid == item["id"]:
240                 models[i] = item
241     write_info(models)
242 
243 
244 # 根据命令选择相应函数
245 def chose_command(commands):
246     command = commands[0]
247     if command == "find":
248         find(commands)
249     if command == "add":
250         add(commands)
251     if command == "del":
252         delete(commands)
253     if command == "update":
254         update(commands)
255 
256 
257 # 输入命令并进行相关处理
258 def input_command():
259     while True:
260         command = input("请输入与增删改查相关命令(q或exit退出程序): ")
261         # 退出程序
262         if command == "exit" or command == "q":
263             exit()
264         # 将字母统一转换成小写
265         order = ""
266         for i in range(len(command)):
267             if command[i].isalpha():
268                 order += command[i].lower()
269             else:
270                 order += command[i]
271         command = order
272         # 分割字符串
273         command = command.split()
274         orders = ["find", "del", "add", "update"]
275         # 确保命令的首个单词正确
276         if command[0] not in orders:
277             print("请输入正确的命令!")
278             continue
279         # 选择命令
280         chose_command(command)
281 
282 
283 if __name__ == '__main__':
284     get_info()
285     input_command()
员工信息增删改查

 

posted @ 2018-04-21 16:59  woz333333  阅读(431)  评论(0编辑  收藏  举报