2019年5月1日 程序的解耦

import os

def file_h(backend_data,res=None,type='search'):
    #程序耦合,文件处理功能 单独拿出来
    if type=='search':
        with open ('test2','r') as read_test2:
            ret = []
            tag=False
            for read_line in read_test2:
                if read_line.strip()==backend_data:#去除/n与/t
                    tag=True
                    continue#注意格式对齐
                if read_line.startswith('backend') and tag:
                    break
                if tag:
                 # print(read_line,end='') #将所有下面的都打印出来
                    ret.append('%s\n'%read_line.strip())
        return ret
    elif type=='change':
        with open('test2', 'r') as read_f, \
                open('test3', 'w') as write_f:
            tag = False
            has_write = False
            for read_line in read_f:
                if read_line.strip() == backend_data:
                    tag = True
                    continue
                if tag and read_line.startswith('backend'):
                    tag = False
                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('test3', 'test2_new')  # 更改文件名



def search(data): #查询
    print('查询功能%s '%data)
    backend_data='backend %s'%data
    return  file_h(backend_data)


def add(data):#增加
    print('增加功能=%s'%data)

def change(data):#修改
    # print('修改功能将更改为%s'%data)
    print('用户输入的是%s'%data)
    backend_data='backend %s'%data[0]
    res=search(data[0])
    print('来自change函数查询到内容', res)
    if not res:
        return '查询到记录不存在'
    else:
        res.append(data[1] + '\n')
        print(res)

    res.insert(0, '%s\n' % backend_data)  # 第一行增加backend sxj
    file_h(backend_data,res=res,type='change')

 

posted @ 2019-05-01 21:05  小圣庄  阅读(139)  评论(0编辑  收藏  举报