# coding = utf-8

 import os
import json
import re
'''
本程序旨在将练习基础知识部分,包括:
列表,元组,字典,文件,函数,字符串等知识
实现的功能:
1.查询
2.删除
3.更改
4.增加
''' #定义的文档存储格式
mes_style = '''bankend www.baidu.org
server 192.168.50.21 wight 100 maxconn 300
bankend www.oldboy.org
server 192.168.99.31 wight 50 maxconn 100\n
''' #用户只能修改这些字段的值
updateable ={
1:"server",
2:"wight",
3:"maxconn"
} #菜单
menu_info = '''
1.查询
2.删除
3.修改
4.添加
5.退出
''' #展示菜单
def show_menu():
'''
to display the menu ,I chosed the str to show it '''
print(menu_info) #初始化操作,往文件里边添加格式文件
def before_start():
'''
before start,you can call this func to create a file
and then you should explanatory(注释) this method before calling
the main method
'''
f = open("web.property","a+",encoding="utf-8")
for i in mes_style:
f.writelines(i)
f.close()
#before_start()
#查询记录
def search(user_enter):
'''
this function can be used when search function needed
user can select the listed item and then,the corresponding
entry will be display
'''
#查询并打印出用户查询关键字所在的行和下一行
f = open("web.property","r",encoding="utf-8")
list = f.readlines()
for i,line in enumerate(list):
if user_enter in line:
print(line)
print(list[i+1])
elif i == len(list)-1:
print("查无结果")
f.close() #查出所有的文件内容,并包装成字典返回
def searchall():
'''
this function is a common function ,it can used in delete and update,so add
'''
f = open("web.property", "r", encoding="utf-8")
list = f.readlines()
#用来存储找到value为空所对应的key
list1 =[]
mapc = {}
for i,line in enumerate(list):
if line == "\n" or line == "":
list.pop(i)
for i in range(0,len(list),2):
mapc[int(i/2)+1] =list[i:i+2]
f.close()
return mapc
#删除
def delete():
'''
this function is used to delete the record user selected
'''
flag = True
while flag:
maps = searchall()
for i in maps.items():
print(i)
user_selected = input("请选择要删除的对象(输入b返回):")
if user_selected.isdigit():
user_selected = int(user_selected)
#print(list)
for j in maps.keys():
if user_selected == j:
temp = j
for m in maps.items():
if user_selected == m:
temp = m
#删除文件中对应的该条记录
for line in list(maps.keys()):
if temp== line:
maps.pop(temp)
file_path = "C:/Users/Administrator/PycharmProjects/pythondemo/web.propertybak"
if os.path.exists(file_path):
os.remove(file_path)
os.renames("web.property", "web.propertybak")
f6 = open("web.property", "w")
for line in maps.values():
f6.write(line[0])
f6.write(line[1])
f6.close()
break
else:
break
print(maps)
#询问是否继续
conti = input("是否继续删除?(y/n):")
if conti == "y":
continue
else:
flag = False
break
elif user_selected == "b":
break
else:
print("输入有错误,请重新选择") #添加
def add():
'''
you can execute add funciton to add a node to file
but you should according to those forms
1:"server",
2:"wight",
3:"maxconn"
'''
#regs ={"bankend":"www.\w.com","server":"\d.\d.\d.\d"} while True:
print("请依次填入下列选项中的值")
bankend = input("bankend:")
server = input("server:")
wight = input("wight:")
maxconn = input("maxconn:")
# 正则表达式检查输入是否符合格式要求
if re.compile(r"www\.(\w+)(\.com|\.cn|\.org|\.net)").match(bankend):
print("bankend ok")
if re.compile(r"\d+\.\d+\.\d+\.\d").match(server):
print("server ok")
if re.compile(r"\d").match(wight):
print("wight ok")
if re.compile(r"\d").match(maxconn):
print("maxconn ok")
#条件都符合
write_date =["bankend %s\n"%bankend," server %s wigth %d maxconn %d"%(server,int(wight),int(maxconn))]
f = open("web.property", "a", encoding="utf-8")
for line in write_date:
f.writelines(line)
f.close()
break
else:
print("maxconn invalid")
continue
else:
print("wight invalid")
continue
else:
print("server invalid")
continue
else:
print("bankend invalid")
continue #更新
def update():
'''
this function is designed for update the file message,content
'''
state = 0
while True:
mapa = searchall()
for i,m in enumerate(mapa):
print(str(i+1)+"."+str(mapa[m]))
it = input("请选择要更改的条目:(b 返回)")
if it.isdigit():
it = int(it)
for i in mapa.keys():
if it == i:
print("check pass")
while True:
for member in updateable:
print(str(member)+":"+updateable[member])
user_se = input("请选择要修改的字段(按b返回):")
if user_se.isdigit():
user_se =int(user_se)
for j in updateable.keys():
if user_se == j:
print("check pass2")
while True:
update_to = input("请输入值:")
if update_to==None or update_to=="":
pass
else:
break
print(user_se)
#获得选择的字段
map_attr = updateable[user_se]
li =[]
for l in mapa[it]:
if map_attr in l:
li.append(l.split(" "))
print(l)
#print(li)
for i,ind in enumerate(li[0]):
if(map_attr in ind and map_attr == "server"):
ind = " "+map_attr+" "+(str(update_to) if update_to.isdigit() else update_to)
elif (map_attr in ind ):
ind = " " + map_attr + " " + (str(update_to) if update_to.isdigit() else update_to)
li[0][i]=ind
break
#同步到mapa
final_str =""
for i in li[0]:
if "server" in i:
final_str += " "+i+" "
elif "wight" in i:
final_str +=i+" "
else:
final_str += i
#print(final_str)
for i,n in enumerate(mapa[it]):
if "server" in n:
mapa[it][i] =final_str+"\n"
print(mapa)
with open("web.property","w") as f:
for line in mapa.values():
f.writelines(line)
f.close()
print(mapa)
print(li)
print("修改成功")
break
elif j == len(updateable):
print("不在选项内,请重新选择")
elif user_se == "b":
break
elif i ==len(mapa):
print("输入选项不在列表中,请重新选择")
elif it == "b":
state = 1
break
else:
print("输入有误")
if state == 1:
return #主程序
while True:
show_menu()
selected = input("请选择:(1,2,3,4,5):")
if selected.isdigit():
selected = int(selected)
if selected == 1:
search(input("请输入要查询的网址:"))
if selected == 2:
delete()
if selected == 3:
update()
if selected == 4:
add()
if selected == 5:
break
else:
print("你输入了其他字符,请输入数字")
continue

python文件实现增删改查操作的更多相关文章

  1. python字典的增删改查操作

    一.字典  (键值对) 1.字典的基本格式:{key1:1,key2:2} 2.字典里的键必须是不可变的(如:数字,字符串,元组,bool值);值是可变的,可用数字,字符串,列表,字典等. 3.字典里 ...

  2. Java使用DOM4J对XML文件进行增删改查操作

    Java进行XML文件操作,代码如下: package com.founder.mrp.util; import java.io.File; import java.util.ArrayList; i ...

  3. python 字典dict 增删改查操作

    初始化: a. data_dict = {} b. data_dict1 = dict() c. data_dict2 = {'key':'value'} 新增: a. data_dict[key]= ...

  4. python 元组tuple 增删改查操作

    初始化: data_tuple = () data_tuple1 = (1,) data_tuple2 = tuple() 新增: data_tuple+data_tuple1 (data_tuple ...

  5. Python文件操作-文件的增删改查

    需求:对文件进行增删改查 由于时间原因,本次代码没有增加任何注释,如有疑问,请联系编辑者:闫龙 其实我也是醉了,看着这些个代码,我脑袋也特么大了,没办法,大神说了,不让用新知识,只可以使用学过的,所以 ...

  6. python 全栈开发,Day124(MongoDB初识,增删改查操作,数据类型,$关键字以及$修改器,"$"的奇妙用法,Array Object 的特殊操作,选取跳过排序,客户端操作)

    一.MongoDB初识 什么是MongoDB MongoDB 是一个基于分布式文件存储的数据库.由 C++ 语言编写.旨在为 WEB 应用提供可扩展的高性能数据存储解决方案. MongoDB 是一个介 ...

  7. 48.Python中ORM模型实现mysql数据库基本的增删改查操作

    首先需要配置settings.py文件中的DATABASES与数据库的连接信息, DATABASES = { 'default': { 'ENGINE': 'django.db.backends.my ...

  8. 【练习】Python第四次:实现对文件的增删改查

    一,实现对文件的增删改查 (一),三级菜单的处理结构及退出技巧:使用TAG标记 tag=True while tag: print('leve1') choice=input("level1 ...

  9. 【Python + Mysql】之用pymysql库连接Mysql数据库并进行增删改查操作

    用pip下载pymysql并引用 具体请参考文章: <Python之MySQL数据库增删改查操作> <python3.6 使用 pymysql 连接 Mysql 数据库及 简单的增删 ...

随机推荐

  1. CoreGraphics(转)

    2.CoreGraphics 上面我们讲过,UIBezierPath是CoreGraphics的封装,使用它可以完成大部分的绘图操作,不过更底层的CoreGraphics更加强大. CoreGraph ...

  2. Java 发送Get和Post请求

    package com.htpt.superviseServices.dm.util; import java.io.BufferedReader; import java.io.IOExceptio ...

  3. 烂笔头——JAVA/JSP

    学艺不精,一些小零头放这里备忘 Object[] obj = (Object[])list.get(i);//取list的某个项目 jsp中出现out.println( )和System.out.pr ...

  4. (转)vim 访问系统剪贴板

    原文出处:http://vim.wikia.com/wiki/Accessing_the_system_clipboard Please review this tip: This tip was i ...

  5. 「LuoguP3379」 【模板】最近公共祖先(LCA)

    题目描述 如题,给定一棵有根多叉树,请求出指定两个点直接最近的公共祖先. 输入输出格式 输入格式: 第一行包含三个正整数N.M.S,分别表示树的结点个数.询问的个数和树根结点的序号. 接下来N-1行每 ...

  6. 2018值得选用的五个Linux服务器发行版

    [IT168 编译]据最新统计,目前Linux发行版约有300种,几乎都可以作为服务器系统运行.在Linux早期,几乎所有发行版都是“万能”发行版,专门的Linux服务器发行版并不火热,到21世纪初, ...

  7. HDU2602(01背包)

    Bone Collector Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)To ...

  8. salt api

    #!/usr/bin/env python # -*- coding:utf8 -*- # __author__ = '北方姆Q' import requests import json from d ...

  9. 读取关联数据(EF Core2.1.1)

    对象-关系映射框架比如EF有三种 方式使用 模型中的导航属性来加载关联数据. 一..Lazy Loading.(关联数据在访问导航属性时被透明的加载,不需要特别的代码,自动的加载) 当一个实体第一次读 ...

  10. 2.11 Hive中数据导入导出Import和Export使用

    https://cwiki.apache.org/confluence/display/Hive/LanguageManual+ImportExport 一.Export.Import Export ...