文件操作的补充
1.原始文件
global log 127.0.0.1 local2 daemon maxconn 256 log 127.0.0.1 local2 info defaults log global mode http timeout connect 5000ms timeout client 50000ms timeout server 50000ms option dontlognull listen stats :8888 stats enable stats uri /admin stats auth admin:1234 frontend oldboy.org bind 0.0.0.0:80 option httplog option httpclose option forwardfor log global acl www hdr_reg(host) -i www.oldboy.org use_backend www.oldboy.org if www backend www.oldboy.org server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000 server 100.1.7.8 100.1.7.8 weight 20 maxconn 3000 server 100.1.7.7 100.1.7.6 weight 20 maxconn 3000 backend ccc.oldboy.org server 100.1.7.9 100.1.7.9 weight 20 maxconn 300
2.操作要求:
3.思路分析
1)一行一行读取,遇到第一个backend做标记,把下面内容加入列表,遇到第二个backend停止添加。
2)思路一:把内容添加进列表,然后把列表内容写入。
思路二:读一行,写一行,直到写到第二个backend,再此之前插入内容即可。
4.代码实现:
1)
def chaxun(a): l1=[] title='backend %s' % a with open('mm','r')as f1: flag=False #默认没找到标题 for line in f1: line=line.strip() if line==title: flag=True #找到标题 continue if flag and line.startswith('backend'): flag = False #标题结束 break if flag and line: #找到标题且不是空行 l1.append(line) return l1
思路一:
# a=input('请输入网址:') # a='www.oldboy.org' # b=input('请输入新纪录字典:') b='{"backend":"www.oldboy.org","record":{"server":"100.1.7.6","weight":20,"maxconn":30}}' b=json.loads(b) a=b["backend"] s=b["record"] s="server %s %s weight %s maxconn %s" % (s['server'],s['server'],s['weight'],s['maxconn']) title='backend %s' % a l1=chaxun(a) l1.append(s) print(l1) with open('mm') as read_obj, open('nn', 'w') as write_obj: flag = False #默认没有找到目标标题 has_write = False #默认列表内容还没有写 for line in read_obj: if line.strip() == title: write_obj.write(line) flag = True #找到标题 continue if flag and line.strip().startswith('backend'): flag = False #标题结束 if flag: #如果已经找到目标标题 if not has_write: #如果还没有写内容 for new_line in l1: temp = "%s %s \n" %(" "*8, new_line) write_obj.write(temp) has_write = True #列表内容书写完毕,即使flag=True,即使没遇到下一个backend,也不会书写内容 else: # 写入上下部分 write_obj.write(line)
思路二:
# a=input('请输入网址:') # a='www.oldboy.org' # b=input('请输入新纪录字典:') b='{"backend":"www.oldboy.org","record":{"server":"100.1.7.6","weight":20,"maxconn":30}}' b=json.loads(b) a=b["backend"] s=b["record"] s="server %s %s weight %s maxconn %s" % (s['server'],s['server'],s['weight'],s['maxconn']) title='backend %s' % a l1=chaxun(a) l1.append(s) print(l1) with open('mm') as read_obj, open('nn', 'w') as write_obj: flag = False #默认没有找到目标标题 for line in read_obj: if line.strip() == title: write_obj.write(line) flag = True #找到标题 continue if flag and line.strip().startswith('backend'): write_obj.write("%s%s \n" %(" "*8, s)) write_obj.write(line) flag = False #标题结束 else: # 写入上下部分 write_obj.write(line)