Python开发【第七篇】:文件处理,文件的增删查改功能

主要的目的

1、函数

2、文件处理

3、tag的用法

4、程序的解耦

实现代码

#!/usr/bin/python3
import os
def file_handler(backend_data, res = None,type = 'fetch'):
    if type == 'fetch':
        with open('haproxy.conf', 'r') as f:
            tag = False
            ret = []
            for line in f:
                if line.strip() == backend_data:
                    tag = True
                    continue

                if line.startswith('backend'): break

                if tag:
                    print('\033[1;45m%s\n\033[0m' % line.strip(), end='')
                    ret.append(line)
            return ret
    elif type == 'change':
        with open('haproxy.conf', 'r') as read_f, \
                open('haproxy.conf_new', 'w') as write_f:
            tag = False
            has_write = False
            for read_line in read_f:  # server
                if read_line.startswith('backend'):
                    tag = False
                if read_line.strip() == backend_data:
                    tag = True
                    continue
                if not tag:
                    write_f.write(read_line)
                else:
                    if not has_write:
                        for record in res:
                            write_f.write(record)
                        has_write = True
    os.rename('haproxy.conf', 'haproxy.conf.bak')
    os.rename('haproxy.conf_new', 'haproxy.conf')
    os.remove('haproxy.conf.bak')

def fetch(data):
    print('查询功能')
    print('\033[1;43m用户数据是\033[0m',data)
    backend_data = 'backend %s'%(data)

    return file_handler(backend_data)

def add():
    pass


 # [{'backend':'www.oldboy1.org','record':{'server':'2.2.2.4','weight':20,'maxconn':3000}},{'backend':'www.oldboy1.org','record':{'server':'2.2.2.5','weight':30,'maxconn':4000}}]
def change(data):
    print('这是修改功能')
    backend = data[0]['backend'] #文件中的一条记录 www.oldboy1.org
    backend_data = 'backend %s'%backend #backend  www.oldboy1.org
    # 原数据格式  server 101.1000.7.9 101.1000.7.9 weight 20 maxconn 30
    old_server_record = '%s server %s %s weight %s maxconn %s\n'%(' '* 7,data[0]['record']['server'],
                                                             data[0]['record']['server'],
                                                             data[0]['record']['weight'],
                                                             data[0]['record']['maxconn'])
    new_server_record = '%s server %s %s weight %s maxconn %s\n' % (' ' * 7, data[1]['record']['server'],
                                                                  data[1]['record']['server'],
                                                                  data[1]['record']['weight'],
                                                                  data[1]['record']['maxconn'])
    res = fetch(backend)  #查询文件中的一条记录
    res.insert(0,'%s\n'%backend_data)
    print('来自change函数-----> ',res)
    if not res or old_server_record not in res:
        return '你要修改的记录不存在'
    else:
        index = res.index(old_server_record)
        res[index] = new_server_record
    file_handler(backend_data, res = res, type = 'change')
def delete():
    pass
#[{'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':20,'maxconn':3000}}]
#执行的功能,测试代码在这下面下
if __name__ == '__main__':
    msg = """
    1:查询
    2:添加
    3:修改
    4:删除
    5:退出
    """
    msg_dict = {'1':fetch,
                '2':add,
                '3':change,
                '4':delete
                }
    while True:
        print(msg)
        choice = input('请输入功能:').strip()
        if not choice :continue
        if choice == '5':break

        data =input('请输入你的数据').strip()

        #除了查询其他功能都要加一个字符串转对应的数据结构的类型,因为通过input输入的内容是字符串类型的
        if choice != '1':
            data = eval(data)

        res = msg_dict[choice](data)
        print(res)

 注意:

修改文件名

#首先先添加模块

import  os

#将 haproxy.conf 修改为 haproxy.conf.bak,就是修改个文件名

os.rename('haproxy.conf','haproxy.conf.bak') 
os.rename('haproxy.conf_new','haproxy.conf')
os.remove('haproxy.conf.bak')

  • 14
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值