# 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. SpringBoot-(2)-Web的json接口,静态网页,动态页面

    一, 了解注解@Controller和@RestController @Controller:处理Http请求 @RestController:Spring4以后新增注解,相当于@Controller ...

  2. 【LeetCode】Rotate List

    Given a list, rotate the list to the right by k places, where k is non-negative. For example:Given 1 ...

  3. jquery特效(2)—选项卡

    最近公司有个页面正好用到了选项卡,我就写了一下,感觉还不错,都挺简单的. 下面来看动态效果: 一.主体程序 <!DOCTYPE html> <html> <head> ...

  4. Jquery Plugin模版

    1. [代码][JavaScript]代码 01// remember to change every instance of "pluginName" to the name o ...

  5. 使用Dubbo实现RPC调用

    启动Dubbo服务有2个方式,1是通过xml配置,2是通过注解来实现,这点和Spring相似. 采用XML配置如下: <?xml version="1.0" encoding ...

  6. 【错误信息】springMVC No mapping found for HTTP request with URI

    出现这个问题的原因是在web.xml中配置错了:

  7. C# 多线程控制 通讯 和切换

    一.多线程的概念  Windows是一个多任务的系统,如果你使用的是windows 2000及其以上版本,你可以通过任务管理器查看当前系统运行的程序和进程.什么是进程呢?当一个程序开始运行时,它就是一 ...

  8. 精选Java面试题

    什么是隐式类型转换?什么是显示类型转换? 当将占位数少的类型赋值给占位数多的类型时,Java自动使用隐式类型转换(如int型转为long型).当把在级别高的变量的值赋给级别底变量时,必须使用显示类型转 ...

  9. hdu-5773 The All-purpose Zero(LIS)

    题目链接: The All-purpose Zero Time Limit: 2000/1000 MS (Java/Others)     Memory Limit: 65536/65536 K (J ...

  10. bzoj2257瓶子与燃料——最大公约数

    题目:https://www.lydsy.com/JudgeOnline/problem.php?id=2257 可以知道最终能够导出的燃料一定是瓶子容量的gcd的倍数,所以此题转化为求n个数中k个数 ...