文件重命名(修改后保存)
import os # os.rename('a.txt','a.txt.bak') os.rename('b.txyt','a.txt')
tag用法 (退出层级,tag用来退回根部)
tag=True while tag: print('leve1') choice=input("level1>>: ").strip() if choice == 'quit':break if choice == 'quit_all': tag = False while tag: print('level2') choice = input("level2>>: ").strip() if choice == 'quit': break if choice == 'quit_all': tag = False while tag: print('level3') choice = input("level3>: ").strip() if choice == 'quit': break if choice == 'quit_all': tag = False
查询,修改文件代码 (使用file_handle来处理文件)
#_*_coding:utf-8_*_ import os def file_handle(filename,backend_data,record_list=None,type='fetch'): #type:fetch append change new_file=filename+'_new' bak_file=filename+'_bak' if type == 'fetch': r_list = [] with open(filename, 'r') as f: tag = False for line in f: if line.strip() == backend_data: tag = True continue if tag and line.startswith('backend'): break if tag and line: r_list.append(line.strip()) for line in r_list: print(line) return r_list elif type == 'append': with open(filename, 'r') as read_file, open(new_file, 'w') as write_file: for r_line in read_file: write_file.write(r_line) for new_line in record_list: if new_line.startswith('backend'): write_file.write(new_line + ' ') else: write_file.write("%s%s " % (' ' * 8, new_line)) os.rename(filename, bak_file) os.rename(new_file, filename) os.remove(bak_file) elif type == 'change': with open(filename, 'r') as read_file, open(new_file, 'w') as write_file: tag=False has_write=False for r_line in read_file: if r_line.strip() == backend_data: tag=True continue if tag and r_line.startswith('backend'): tag=False if not tag: write_file.write(r_line) else: if not has_write: for new_line in record_list: if new_line.startswith('backend'): write_file.write(new_line+' ') else: write_file.write('%s%s ' %(' '*8,new_line)) has_write=True os.rename(filename, bak_file) os.rename(new_file, filename) os.remove(bak_file) def fetch(data): backend_data="backend %s" %data return file_handle('haproxy.conf',backend_data,type='fetch') def add(data): backend=data['backend'] record_list=fetch(backend) current_record="server %s %s weight %s maxconn %s" %(data['record']['server'], data['record']['server'], data['record']['weight'], data['record']['maxconn']) backend_data="backend %s" %backend if not record_list: record_list.append(backend_data) record_list.append(current_record) file_handle('haproxy.conf',backend_data,record_list,type='append') else: record_list.insert(0,backend_data) if current_record not in record_list: record_list.append(current_record) file_handle('haproxy.conf',backend_data,record_list,type='change') def remove(data): backend=data['backend'] record_list=fetch(backend) current_record="server %s %s weight %s maxconn %s" %(data['record']['server'], data['record']['server'], data['record']['weight'], data['record']['maxconn']) backend_data = "backend %s" % backend if not record_list or current_record not in record_list: print('