python练习:文件操作
文件 proxy:
frontend oldboy.com bind 0.0.0.0 use_backend www.oldboy.com if www backend www.oldboy.com server 10.2.1.9 weight 20 maxcom 300
要求:
查询域名是否存在,存在询问修改删除,不存在询问是否添加
1 #!/usr/bin/env python 2 #coding:utf-8 3 4 5 proxy_file="proxy" 6 7 while True: 8 domain=input('请输入域名:') 9 10 domain_line=' '.join(['backend',domain]) 11 12 if domain_line=='q': 13 print('quit!') 14 break 15 16 line_index='' 17 content_lines='' 18 with open(proxy_file,'r') as f: 19 content_lines= f.readlines() 20 for index,line in enumerate(content_lines): 21 if domain_line in line: 22 if not 'use' in line: 23 line_index=index 24 25 26 if line_index: 27 print('-----------查找到域名 {domain} 的记录:-----------'.format(domain=domain)) 28 print(content_lines[line_index].strip()) 29 print(content_lines[line_index+1].strip()) 30 else: 31 print('记录不存在!') 32 33 action_str='请输入您的操作'.center(50,'-') 34 action_str=''.join([action_str,'\nq:quit\n']) 35 if line_index: 36 action_str=''.join([action_str,'u:update\n']) 37 action_str=''.join([action_str,'d:delete']) 38 else: 39 action_str=''.join([action_str,'a:add']) 40 41 action_input=input(action_str) 42 43 if action_input=='q': 44 print('quit!') 45 break 46 elif action_input=='d' and line_index and content_lines: 47 with open(proxy_file,'w') as f: 48 for index,line in enumerate(content_lines): 49 if index==line_index or index==line_index+1: 50 continue 51 f.write(line) 52 53 elif action_input=='u' and line_index and content_lines: 54 new_domain='''{ 55 'backend':'www.2014520.cn', 56 'record':{ 57 'server':'2.2.2.2', 58 'weight':20, 59 'maxconn':30 60 61 } 62 63 }''' 64 new_domain=eval(new_domain) 65 backend=new_domain['backend'] 66 server=new_domain['record']['server'] 67 weight=new_domain['record']['weight'] 68 maxconn=new_domain['record']['maxconn'] 69 70 _line_backend='backend {backend}\n'.format(backend=backend) 71 _line_record=' server {server} weight {weight} maxconn {maxconn}'.format(server=server,weight=weight,maxconn=maxconn) 72 73 74 with open(proxy_file,'w') as f: 75 for index,line in enumerate(content_lines): 76 if index==line_index : 77 f.write(_line_backend) 78 elif index==line_index+1: 79 f.write(_line_record) 80 else: 81 f.write(line) 82 elif action_input=='a': 83 84 new_domain='''{ 85 'backend':'www.baidu.cn', 86 'record':{ 87 'server':'12.5.2.8', 88 'weight':30, 89 'maxconn':50 90 91 } 92 93 }''' 94 new_domain=eval(new_domain) 95 backend=new_domain['backend'] 96 server=new_domain['record']['server'] 97 weight=new_domain['record']['weight'] 98 maxconn=new_domain['record']['maxconn'] 99 100 _line_backend='backend {backend}\n'.format(backend=backend) 101 _line_record=' server {server} weight {weight} maxconn {maxconn}'.format(server=server,weight=weight,maxconn=maxconn) 102 with open(proxy_file,'a') as f: 103 f.write(_line_backend) 104 f.write(_line_record) 105 else: 106 107 print("输入有误!") 108 continue