文件的增删改查

有以下员工信息表

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

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)
时间: 2024-10-06 00:48:53

文件的增删改查的相关文章

MyBatis学习(二)、SQL语句映射文件(2)增删改查、参数、缓存

二.SQL语句映射文件(2)增删改查.参数.缓存 2.2 select 一个select 元素非常简单.例如: Xml代码   <!-- 查询学生,根据id --> <select id="getStudent" parameterType="String" resultMap="studentResultMap"> SELECT ST.STUDENT_ID, ST.STUDENT_NAME, ST.STUDENT_SEX

Python基础-----实现文件的增删改查

实现文件的增删改查 1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 import os 4 def file_handler(backend_data,res = None,type = 'fetch'): #文件处理函数 5 if type == 'fetch': #查询操作 6 with open('haproxy.conf','r') as read_f: 7 tag = False #初始状态标识 8 ret = [] #用于放置查询

对*.ini文件的增删改查

文件的格式有很多种 *.ini 一般是带一个齿轮的配置文件,这个文件的操作有专门的类库进行处理不行自己硬编码      ini4j.jar 这个jar包专门封装了处理*.ini文件的方法. 1 public interface IParaManager { 2 public int getKey(String section, String key, CInt value); 3 public int getkey(String section, String key, CString valu

Python 模拟SQL对文件进行增删改查

1 #!/usr/bin/env python 2 # _*_ coding:UTF-8 _*_ 3 # __auth__: Dalhhin 4 # Python 3.5.2,Pycharm 2016.3.2 5 # 2017/05/15 6 7 import sys,os 8 9 def where(dbfile,where_list): #条件是一个list 10 11 def and_or_where(sub_where_list): 12 '''获取and或同时含有and.or关键字的条

对文件的增删改查 以及 ---三次登陆

文件 global log 127.0.0.1 local2 daemon maxconn 256 log 127.0.0.1 local2 info defaults log global mode http timeout connect 5000ms timeout client 50000ms timeout server 50000ms option dontlognull listen stats :8888 stats enable stats uri /admin stats a

Day5.对文件的增删改查+三次登陆后锁定

作业1:对文件haproxy.conf进行增删改查: haproxy.conf原文件内容如下: global log 127.0.0.1 local2 daemon maxconn 256 log 127.0.0.1 local2 info defaults log global mode http timeout connect 5000ms timeout client 50000ms timeout server 50000ms option dontlognull listen stat

04-09,Work-对文件的增删改查(函数)

#增删改查之查def look(): while 1 : enter = input("查看:如www.oldboy.org\n") l = [] flag = False with open("haproxy.conf") as enter_read: for line in enter_read: if line.startswith("backend") and enter in line: flag = True continue if

iOS Plist文件,增删改查

今天早上,9点开始弄Plist,然后一直写,一直写(中午取出40分钟吃饭时间),写到1点,写完了,交给头,头说,不是这个意思.我是每个用户创建了一个文件夹,在这个用户的文件夹里面,分别根据应用创建了文件夹,将Plist文件存在这个应用的文件夹中.头说:就只有一个Plist,这个Plist的命名是以用户名称来命名的,每个应用的名称和信息,记录在这个Plist文件里面.这个Document里面,只有一个Plist了..刚睡醒午觉的我,灰灰地又回去改,有了上午的经验,半个小时,就弄出来了.去给头请示,

python文件的增删改查操作

1 def choice(): 2 print(''' 3 1 查找 4 2 删除 5 3 添加 6 4 修改 7 ''') 8 def forlist(): 9 with open("test2", encoding="utf8", mode="r+") as w: 10 for line in w: 11 print(line.strip()) 12 13 14 def check(): 15 usr=input("输入你要查找的域