python ------- 文件处理之增删改查-------作业
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python ------- 文件处理之增删改查-------作业相关的知识,希望对你有一定的参考价值。
有点小bug,还待改进,代码如下:
1.查询:
输入:www.ordboy1.org
1 list = [] #创建一个空列表 2 flag = False #设置一个开关 3 input1 = input("plesae your input "www.oldboy1.org" :") 4 with open("haproxy.conf",encoding="utf-8") as f_read: #把源文件以utf-8格式打开到f_read 5 for line in f_read: #遍历文件到line这个变量中 6 if line.startswith("backend") and input1 in line: 7 flag = True 8 continue #跳出本层循环 9 10 if line.startswith("backend"): #判断字符串是否以backend开头 11 break 12 if flag: 13 list.append(line.strip()) #追加到空列表 14 print("hello".center(50,"-")) 15 16 for i in list: #遍历列表 17 print(i)
2.删除:
输入:{"backend":"www.oldboy20.org","record":{"server":1111,"weight":2222,"maxconn":3333}}
1 choice = input("please your input is {} :") 2 # {"backend":"www.oldboy20.org","record":{"server":1111,"weight":2222,maxconn:3333}} 3 dic = eval(choice) # 把输入的字符串转成字典 4 tltle = dic["backend"] 5 tetle1 = dic["record"] #这个没有用 6 with open("haproxy.conf", encoding="utf-8") as f_read, open("test5", "w", encoding="utf-8") as w_write: 7 8 for line in f_read: 9 w_write.write(line) 10 if line.startswith("backend") and tltle in line: 11 # w_write.write(line) 12 break
3.增加:
输入:{"backend":"www.oldboy20.org","record":{"server":1111,"weight":2222,"maxconn":3333}}
1 choice = input("please your input is {} : ") 2 # {"backend":"www.oldboy20.org","record":{"server":1111,"weight":2222,"maxconn":3333}} 3 dic = eval(choice) # 把字符串转成字典 4 title = dic[‘backend‘] # "www.oldboy20.org" 5 record = dic[‘record‘] 6 r_s = ‘ server %s weight %s maxconn %s\n‘ 7 % (record[‘server‘], record[‘weight‘], record[‘maxconn‘]) 8 9 with open("haproxy.conf", encoding="utf-8") as f_read, open("test3", mode="w", encoding="utf-8") as w_read: 10 for line in f_read: 11 w_read.write(line) 12 if line.startswith(‘backend‘) and title in line: 13 # print(‘11111>‘) 14 w_read.write(r_s) 15 # w_read.write(‘=====>‘) 16 w_read.flush()
4.修改:
输入:{"backend":"www.oldboy20.org","record":{"server":1111,"weight":2222,"maxconn":3333}}
1 choice = input("please your input is {} :") 2 # {"backend":"www.oldboy20.org","record":{"server":1111,"weight":2222,"maxconn":3333}} 3 dic = eval(choice) #把输入的字符串转成字典 4 tltel = dic["backend"] 5 tltel1 = dic["record"] 6 dic["record"]["server"] = "0000" 7 dic["record"]["weight"] = "0000" 8 dic["record"]["maxconn"] = "0000" 9 # print(dic) 10 #格式化字符串 11 r_s = " server %s weight %s maxconn %s" % (tltel1["server"], tltel1[‘weight‘], tltel1["maxconn"]) 12 with open("haproxy.conf", encoding="utf-8") as f_read, open("test6", mode="w", encoding="utf-8") as w_write: 13 for line in f_read: 14 w_write.write(line) # 把line中的字符串写到w_write中 15 if line.startswith("backend") and tltel in line: #判断 line中字符串否以“backend”开头,并且满不满足tetle在这行 16 w_write.write(r_s) #把字符串写入到w_rite中 17 break #跳出循环
以上是关于python ------- 文件处理之增删改查-------作业的主要内容,如果未能解决你的问题,请参考以下文章