• python文件实现增删改查操作


      1 # coding = utf-8
      2 
      3 import os
      4 import json
      5 import re
      6 '''
      7 本程序旨在将练习基础知识部分,包括:
      8 列表,元组,字典,文件,函数,字符串等知识
      9 实现的功能:
     10 1.查询
     11 2.删除
     12 3.更改
     13 4.增加
     14 '''
     15 
     16 #定义的文档存储格式
     17 mes_style = '''bankend    www.baidu.org
     18            server 192.168.50.21   wight 100   maxconn 300
     19 bankend    www.oldboy.org
     20            server 192.168.99.31   wight 50   maxconn 100
    
     21 '''
     22 
     23 #用户只能修改这些字段的值
     24 updateable ={
     25     1:"server",
     26     2:"wight",
     27     3:"maxconn"
     28 }
     29 
     30 #菜单
     31 menu_info = '''
     32 1.查询
     33 2.删除
     34 3.修改
     35 4.添加
     36 5.退出
     37 '''
     38 
     39 
     40 
     41 #展示菜单
     42 def show_menu():
     43     '''
     44     to display the menu ,I chosed the str to show it
     45 
     46     '''
     47     print(menu_info)
     48 
     49 #初始化操作,往文件里边添加格式文件
     50 def before_start():
     51     '''
     52     before start,you can call this func to create a file
     53     and then you should explanatory(注释) this method before calling
     54     the main method
     55     '''
     56     f = open("web.property","a+",encoding="utf-8")
     57     for i in mes_style:
     58         f.writelines(i)
     59     f.close()
     60 #before_start()
     61 #查询记录
     62 def search(user_enter):
     63     '''
     64     this function can be used when search function needed
     65    user can select the listed item and then,the corresponding
     66    entry will be display
     67     '''
     68     #查询并打印出用户查询关键字所在的行和下一行
     69     f = open("web.property","r",encoding="utf-8")
     70     list = f.readlines()
     71     for i,line in enumerate(list):
     72         if user_enter in line:
     73             print(line)
     74             print(list[i+1])
     75         elif i == len(list)-1:
     76             print("查无结果")
     77     f.close()
     90 
     91 #查出所有的文件内容,并包装成字典返回
     92 def searchall():
     93     '''
     94     this function is a common function ,it can used in delete and update,so add
     95     '''
     96     f = open("web.property", "r", encoding="utf-8")
     97     list = f.readlines()
     98     #用来存储找到value为空所对应的key
     99     list1 =[]
    100     mapc = {}
    101     for i,line in enumerate(list):
    102         if line == "
    " or line == "":
    103             list.pop(i)
    104     for i in range(0,len(list),2):
    105         mapc[int(i/2)+1] =list[i:i+2]
    106     f.close()
    107     return mapc
    108 #删除
    109 def delete():
    110     '''
    111     this function is used to delete the record user selected
    112     '''
    113     flag = True
    114     while flag:
    115         maps = searchall()
    116         for i in maps.items():
    117             print(i)
    118         user_selected = input("请选择要删除的对象(输入b返回):")
    119         if user_selected.isdigit():
    120             user_selected = int(user_selected)
    121             #print(list)
    122             for j in maps.keys():
    123                 if user_selected == j:
    124                     temp = j
    125             for m in maps.items():
    126                 if user_selected == m:
    127                     temp = m
    128                     #删除文件中对应的该条记录
    129                     for line in list(maps.keys()):
    130                         if temp== line:
    131                             maps.pop(temp)
    132                             file_path = "C:/Users/Administrator/PycharmProjects/pythondemo/web.propertybak"
    133                             if os.path.exists(file_path):
    134                                 os.remove(file_path)
    135                             os.renames("web.property", "web.propertybak")
    136                             f6 = open("web.property", "w")
    137                             for line in maps.values():
    138                                 f6.write(line[0])
    139                                 f6.write(line[1])
    140                             f6.close()
    141                             break
    142                         else:
    143                             break
    144                     print(maps)
    145                     #询问是否继续
    146                     conti = input("是否继续删除?(y/n):")
    147                     if conti == "y":
    148                         continue
    149                     else:
    150                         flag = False
    151                         break
    152         elif user_selected == "b":
    153             break
    154         else:
    155             print("输入有错误,请重新选择")
    156 
    157 
    158 #添加
    159 def add():
    160     '''
    161     you can execute add funciton to add a node to file
    162     but you should according to those forms
    163     1:"server",
    164     2:"wight",
    165     3:"maxconn"
    166     '''
    167     #regs ={"bankend":"www.w.com","server":"d.d.d.d"}
    168 
    169 
    170     while True:
    171         print("请依次填入下列选项中的值")
    172         bankend = input("bankend:")
    173         server = input("server:")
    174         wight = input("wight:")
    175         maxconn = input("maxconn:")
    176         # 正则表达式检查输入是否符合格式要求
    177         if re.compile(r"www.(w+)(.com|.cn|.org|.net)").match(bankend):
    178             print("bankend ok")
    179             if re.compile(r"d+.d+.d+.d").match(server):
    180                 print("server ok")
    181                 if re.compile(r"d").match(wight):
    182                     print("wight ok")
    183                     if re.compile(r"d").match(maxconn):
    184                         print("maxconn ok")
    185                         #条件都符合
    186                         write_date =["bankend    %s
    "%bankend,"           server %s   wigth %d   maxconn %d"%(server,int(wight),int(maxconn))]
    187                         f = open("web.property", "a", encoding="utf-8")
    188                         for line in write_date:
    189                             f.writelines(line)
    190                         f.close()
    191                         break
    192                     else:
    193                         print("maxconn invalid")
    194                         continue
    195                 else:
    196                     print("wight invalid")
    197                     continue
    198             else:
    199                 print("server invalid")
    200                 continue
    201         else:
    202             print("bankend invalid")
    203             continue
    204 
    205 
    206 #更新
    207 def update():
    208     '''
    209     this function is designed for update the file message,content
    210     '''
    211     state = 0
    212     while True:
    213         mapa = searchall()
    214         for i,m in enumerate(mapa):
    215             print(str(i+1)+"."+str(mapa[m]))
    216         it = input("请选择要更改的条目:(b 返回)")
    217         if it.isdigit():
    218             it = int(it)
    219             for i in mapa.keys():
    220                 if it == i:
    221                     print("check pass")
    222                     while True:
    223                         for member in updateable:
    224                             print(str(member)+":"+updateable[member])
    225                         user_se = input("请选择要修改的字段(按b返回):")
    226                         if user_se.isdigit():
    227                             user_se =int(user_se)
    228                             for j in updateable.keys():
    229                                 if user_se == j:
    230                                     print("check pass2")
    231                                     while True:
    232                                         update_to = input("请输入值:")
    233                                         if update_to==None or update_to=="":
    234                                             pass
    235                                         else:
    236                                             break
    237                                     print(user_se)
    238                                     #获得选择的字段
    239                                     map_attr = updateable[user_se]
    240                                     li =[]
    241                                     for  l in mapa[it]:
    242                                         if map_attr in l:
    243                                             li.append(l.split("   "))
    244                                         print(l)
    245                                     #print(li)
    246                                     for i,ind in enumerate(li[0]):
    247                                         if(map_attr in ind and map_attr == "server"):
    248                                             ind = "           "+map_attr+" "+(str(update_to) if update_to.isdigit() else update_to)
    249                                         elif (map_attr in ind ):
    250                                             ind = "  " + map_attr + " " + (str(update_to) if update_to.isdigit()  else update_to)
    251                                             li[0][i]=ind
    252                                             break
    253                                     #同步到mapa
    254                                     final_str =""
    255                                     for i in li[0]:
    256                                         if "server" in i:
    257                                             final_str += "          "+i+"   "
    258                                         elif "wight" in i:
    259                                             final_str +=i+"   "
    260                                         else:
    261                                             final_str += i
    262                                     #print(final_str)
    263                                     for i,n in enumerate(mapa[it]):
    264                                         if "server" in n:
    265                                             mapa[it][i] =final_str+"
    "
    266                                     print(mapa)
    267                                     with open("web.property","w") as f:
    268                                         for line in mapa.values():
    269                                             f.writelines(line)
    270                                     f.close()
    271                                     print(mapa)
    272                                     print(li)
    273                                     print("修改成功")
    274                                     break
    275                                 elif j == len(updateable):
    276                                     print("不在选项内,请重新选择")
    277                         elif user_se == "b":
    278                             break
    279                 elif i ==len(mapa):
    280                     print("输入选项不在列表中,请重新选择")
    281         elif it == "b":
    282             state = 1
    283             break
    284         else:
    285             print("输入有误")
    286     if state == 1:
    287         return
    288 
    289 #主程序
    290 while True:
    291     show_menu()
    292     selected = input("请选择:(1,2,3,4,5):")
    293     if selected.isdigit():
    294         selected = int(selected)
    295         if selected == 1:
    296             search(input("请输入要查询的网址:"))
    297         if selected == 2:
    298             delete()
    299         if selected == 3:
    300             update()
    301         if selected == 4:
    302             add()
    303         if selected == 5:
    304             break
    305     else:
    306         print("你输入了其他字符,请输入数字")
    307         continue
  • 相关阅读:
    [NOIP2017 TG D2T2]宝藏(模拟退火)
    [洛谷P1337][JSOI2004]平衡点 / 吊打XXX
    [洛谷P4940]Portal2
    [CF1073E]Segment Sum
    [CF1066C]Books Queries
    [CF1065C]Make It Equal
    [洛谷P3469][POI2008]BLO-Blockade
    网络模型 ------->MobileNet-v3
    C++--------------------->>>>>>cmakelist的编写
    C++ ----------------》》》》》cmake list的
  • 原文地址:https://www.cnblogs.com/g177w/p/8120410.html
Copyright © 2020-2023  润新知