# 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. mac 中安装redis 以及 安装php-redis扩展过程详细记录

    1. 通过homebrew 安装 redis sodu brew install redis 2. 安装后执行开启redis,采用默认配置, 默认配置只有本地(127.0.0.1)可以访问.需要远程访 ...

  2. TortoiseSVN使用笔记

    TortoiseSVN版本冲突详解   下列步骤展示了如何将分支A中的修改合并到分支B. 1.在分支B的本地副本目录中选择"合并(Merge)". 2.选择“合并一个版本范围(Me ...

  3. eval函数用法

    JavaScript 全局对象 定义和用法 eval() 函数可计算某个字符串,并执行其中的的 JavaScript 代码. 语法 eval(string) 参数 描述 string 必需.要计算的字 ...

  4. HDU4990 Reading comprehension —— 递推、矩阵快速幂

    题目链接:https://vjudge.net/problem/HDU-4990 Reading comprehension Time Limit: 2000/1000 MS (Java/Others ...

  5. 记录下linux好用的命令

    http://mp.weixin.qq.com/s/LU1iAWfssv1x-QMX6hJqmQ

  6. android读取apk中已经存在的数据库信息

    在android数据库编程方面,大家有没有遇到过,我要从指定位置的已经存在的数据库来进行操作的问题.之前我尝试了很多方法都没有成功,后来找到了解决的方法.   下面说明下这段代码的意思,第一步先判断在 ...

  7. 关于Spring Security的笔记

    1.web.xml配置文件 加载Spring Security,将DelegatingFilterProxy配置在DispatcherServlet之前. <filter> <fil ...

  8. BZOJ_3680_吊打XXX_模拟退火

    BZOJ_3680_吊打XXX_模拟退火 Description gty又虐了一场比赛,被虐的蒟蒻们决定吊打gty.gty见大势不好机智的分出了n个分身,但还是被人多势众的蒟蒻抓住了.蒟蒻们将 n个g ...

  9. 【旧文章搬运】从XP到Win7看Windows对象管理的变化(概述)

    原文发表于百度空间,2010-08-01========================================================================== 今天花了一 ...

  10. LWDB

    题意: 给一棵 $n$ 个节点的树,维护两种操作: 1.将距离 $x$ $distance \leq d$ 的点染成 $c$ 2.询问 $x$ 的颜色. 解法: 首先将染色可以转换为每个时间对应一个颜 ...