1. 程式人生 > >Python--綜合練習--對檔案進行增刪改查

Python--綜合練習--對檔案進行增刪改查

知識點應用:strip()
 tag
      函式封裝
      檔案操作
      for迴圈
      os模組
      程式碼解耦

例項
tag = True
while tag:
    print('level')
    choice = input('level1>>:').strip()
    while tag:
        print('level2')
        choice = input('level2>>:').strip()
        if choice == 'quit':break   #
t退到上一層 if choice == 'quit_all': tag = False # 退出全部 while tag: print('level3') choice = input('level3>>>:').strip() if choice == 'quit': break #t退到上一層 if choice == 'quit_all':tag = False #退出全部

未封裝例項

import os   #引入os模組
def fetch(data): #查詢 backend_data = 'backend %s' %data with open('haproxy.conf','r') as read_f: tag = False ret = [] for read_line in read_f: if read_line.strip() == backend_data: #這裡說明匹配到想要的內容 tag = True #tag 的狀態應當要改變 continue
#跳過當前行 ''' 退出規則 當tag = True 時 說明匹配到想要的內容 迴圈檔案是一行一行的迴圈 當backend_data = global、defaults、listen、frontend時都不會進入if裡面執行 當碰見一個backend時 tag變為True並跳出當前迴圈執行下一次迴圈 這時進來的是 server 101.1000.7.9 101.1000.7.9 weight 20 maxconn 30 server 2.2.2.7 2.2.2.7 weight 30 maxconn 4000 server 10.10.10.1 10.10.10.1 weight 22 maxconn 2000 server 2.2.2.5 2.2.2.5 weight 30 maxconn 4000 程式不會執行 if tag and read_line.startswith('backend'): break tag為True狀態沒改變而繼續執行 if tag: print('\033[1;45m%s\033[0m' %read_line,end='') # 列印匹配到的內容 直到又遇到backend www.oldboy2.org 時 執行 if tag and read_line.startswith('backend'): break ''' if tag and read_line.startswith('backend'): # tag = False #tag = False for迴圈依然會執行下去 break if tag: ret.append(read_line) # print('\033[1;45m%s\033[0m' %read_line,end='') # 列印匹配到的內容 return ret def add(): pass def change(data): #修改檔案 backend = data[0]['backend'] #backend = www.oldboy1.org backend_data = 'backend %s' %backend #得到:www.oldboy1.org ''' 拼接字串 :' server 2.2.2.5 2.2.2.5 weight 30 maxconn 4000' ''' old_server_record = '%sserver %s %s weight %s maxconn %s\n' %(' '*8,data[0]['record']['server'],data[0]['record']['server'],data[0]['record']['weight'],data[0]['record']['maxconn']) #print('使用者想要修改的資料是:',old_server_record) new_server_record = '%sserver %s %s weight %s maxconn %s\n' %(' '*8,data[1]['record']['server'],data[1]['record']['server'],data[1]['record']['weight'],data[1]['record']['maxconn']) ''' data[0]是要被修改為data[0]的資料,類似data[0]是存在資料庫中的,即將被更新為data[1] ''' res = fetch(backend) #根據索引查詢出資料 #print(res) if not res or old_server_record not in res: return '你要修改的記錄不存在' else: index = res.index(old_server_record) res[index] = new_server_record res.insert(0,'%s\n' %backend_data) with open('haproxy.conf','r') as read_f,open('haproxy_new.conf','w') as writ_f: tag = False has_write = False for read_line in read_f: if read_line.strip() == backend_data: ''' 原理類似查詢 找到匹配位置,改變狀態tag = True 把修改的列表寫入檔案 ''' tag = True continue if tag and read_line.startswith('backend'): tag = False if not tag: writ_f.write(read_line) else: if not has_write: #防止有多少個server寫多少次 for record in res: writ_f.write(record) has_write = True os.rename('haproxy.conf','haproxy.conf.bak') #備份原始檔 os.rename('haproxy_new.conf','haproxy.conf') #修改新的檔名為原來的檔名 #os.remove('haproxy.conf.bak') #刪除備份檔案 def delete(): pass #data[0]是要被修改為data[0]的資料,類似data[0]是存在資料庫中的,即將被更新為data[1] if __name__ == '__main__': msg = ''' 1:查詢 2:新增 3:修改 4:刪除 5:退出 ''' msg_dic = { '1':fetch, '2':add, '3':change, '4':delete, } while True: print(msg) choice = input('\033[1;43m請輸入您的選項\033[0m:') if not choice:continue if choice == 5:break data = input('請輸入您的資料:').strip() if choice != '1': data = eval(data) ret = msg_dic[choice](data) #拿到查詢到的返回值 print(ret) # [{'backend':'www.oldboy1.org','record':{'server':'2.2.2.5','weight':30,'maxconn':4000}},{'backend':'www.oldboy1.org','record':{'server':'2.2.2.4','weight':3,'maxconn':4000}}]
封裝函式file_handler()  提取檔案處理解耦部分
import os  # 引入os模組

def file_handler(backend_data,res = None,type = 'fetch'):
    if type == 'fetch':
        with open('haproxy.conf', 'r') as read_f:
            tag = False
            ret = []
            for read_line in read_f:
                if read_line.strip() == backend_data:  # 這裡說明匹配到想要的內容
                    tag = True  # tag 的狀態應當要改變
                    continue  # 跳過當前行
                '''
                退出規則
                當tag = True 時 說明匹配到想要的內容
                迴圈檔案是一行一行的迴圈
                當backend_data = global、defaults、listen、frontend時都不會進入if裡面執行
                當碰見一個backend時 tag變為True並跳出當前迴圈執行下一次迴圈
                這時進來的是
                        server 101.1000.7.9 101.1000.7.9 weight 20 maxconn 30
                        server 2.2.2.7 2.2.2.7 weight 30 maxconn 4000
                        server 10.10.10.1 10.10.10.1 weight 22 maxconn 2000
                        server 2.2.2.5 2.2.2.5 weight 30 maxconn 4000

                程式不會執行
                if tag and read_line.startswith('backend'):
                    break
                tag為True狀態沒改變而繼續執行
                if tag:
                    print('\033[1;45m%s\033[0m' %read_line,end='')  # 列印匹配到的內容
                直到又遇到backend www.oldboy2.org 時
                執行
                if tag and read_line.startswith('backend'):
                    break
                '''
                if tag and read_line.startswith('backend'):
                    # tag = False   #tag = False for迴圈依然會執行下去
                    break
                if tag:
                    ret.append(read_line)
                    # print('\033[1;45m%s\033[0m' %read_line,end='')  # 列印匹配到的內容
            return ret
    elif type == 'change':
        with open('haproxy.conf', 'r') as read_f, open('haproxy_new.conf', 'w') as writ_f:
            tag = False
            has_write = False
            for read_line in read_f:
                if read_line.strip() == backend_data:
                    '''
                    原理類似查詢
                    找到匹配位置,改變狀態tag = True
                    把修改的列表寫入檔案
                    '''
                    tag = True
                    continue
                if tag and read_line.startswith('backend'):
                    tag = False
                if not tag:
                    writ_f.write(read_line)
                else:
                    if not has_write:  # 防止有多少個server寫多少次
                        for record in res:
                            writ_f.write(record)
                            has_write = True
        os.rename('haproxy.conf', 'haproxy.conf.bak')  # 備份原始檔
        os.rename('haproxy_new.conf', 'haproxy.conf')  # 修改新的檔名為原來的檔名
        os.remove('haproxy.conf.bak')   #刪除備份檔案


def fetch(data):
    # 查詢
    backend_data = 'backend %s' % data
    return file_handler(backend_data)

def add():
    pass

def change(data):
    # 修改檔案
    backend = data[0]['backend']  # backend = www.oldboy1.org
    backend_data = 'backend %s' % backend  # 得到:www.oldboy1.org
    '''
    拼接字串 :'        server 2.2.2.5 2.2.2.5 weight 30 maxconn 4000'
    '''
    old_server_record = '%sserver %s %s weight %s maxconn %s\n' % (
    ' ' * 8, data[0]['record']['server'], data[0]['record']['server'], data[0]['record']['weight'],
    data[0]['record']['maxconn'])
    # print('使用者想要修改的資料是:',old_server_record)

    new_server_record = '%sserver %s %s weight %s maxconn %s\n' % (
    ' ' * 8, data[1]['record']['server'], data[1]['record']['server'], data[1]['record']['weight'],
    data[1]['record']['maxconn'])
    '''
    data[0]是要被修改為data[0]的資料,類似data[0]是存在資料庫中的,即將被更新為data[1]
    '''
    res = fetch(backend)  # 根據索引查詢出資料
    # print(res)
    if not res or old_server_record not in res:
        return '你要修改的記錄不存在'
    else:
        index = res.index(old_server_record)
        res[index] = new_server_record
    res.insert(0, '%s\n' % backend_data)
    return file_handler(backend_data,res = res,type = 'change')


def delete():
    pass


# data[0]是要被修改為data[0]的資料,類似data[0]是存在資料庫中的,即將被更新為data[1]

if __name__ == '__main__':
    msg = '''
        1:查詢
        2:新增
        3:修改
        4:刪除
        5:退出
    '''
    msg_dic = {
        '1': fetch,
        '2': add,
        '3': change,
        '4': delete,
    }
    while True:
        print(msg)
        choice = input('\033[1;43m請輸入您的選項\033[0m:')
        if not choice: continue
        if choice == 5: break
        data = input('請輸入您的資料:').strip()
        if choice != '1':
            data = eval(data)
        ret = msg_dic[choice](data)  # 拿到查詢到的返回值
        print(ret)

#更新檔案
# [{'backend':'www.oldboy1.org','record':{'server':'101.1000.7.9','weight':20,'maxconn':30}},{'backend':'www.oldboy1.org','record':{'server':'2.2.2.7','weight':213,'maxconn':720}}]