自定配置文件的增删改查

 

# @Time    : 2017/4/18 15:31
# @Author  : Cui X
# @File    : configparser_mod.py


import configparser


class Config(object):
    """置文件操作"""

    def __init__(self, sections, prices):
        self.sections = sections
        self.prices = prices

    # 生成配置文件模板
    @classmethod
    def config_create(cls):
        config = configparser.ConfigParser()
        config["db"] = {'db_host': '192.168.1.1',
                        'db_port': '3306',
                        'db_user': 'root',
                        'db_pass': 'password'}
        # 两种写法,上面是一种,下面是一种
        config['concurrent'] = {}
        config['concurrent']['thread'] = '200'
        config['concurrent']['processor'] = '400'
        config.write(open('test.conf', 'w'))
    # 把数据读出来
    @classmethod
    def config_read(cls):
        conf = configparser.ConfigParser()
        conf.read('test.conf')
        return conf

    # 判断数据是否在存在文件中
    def config_judge(self):
        config = self.config_read()
        if self.sections in config.sections():
            if self.prices in config[self.sections]:
                return True
            else:
                return False
        else:
            return False

    # 增加
    def config_add(self, price):
        if self.config_judge() is False:
            config = self.config_read()
            if self.sections in config.sections():
                config[self.sections][self.prices] = price
                config.write(open('test.conf', 'w'))
                print('数据写入成功')
            else:
                print('%s 不存在' % self.sections)
        else:
            print('数据已存在')

    def config_delete(self):
        if self.config_judge() is True:
            config = self.config_read()
            del config[self.sections][self.prices]
            config.write(open('test.conf', 'w'))
            print('数据删除成功')
        else:
            print('删除的值不存在')

    # 修改配置
    def config_change(self, price):
        if self.config_judge() is True:
            config = self.config_read()
            config[self.sections][self.prices] = price
            config.write(open('test.txt', 'w'))
            print('%s %s 修改成功' % (self.sections, self.prices))

    # 查询配置
    def config_select(self):
        if self.config_judge() is True:
            config = self.config_read()
            select = config[self.sections][self.prices]
            print(select)

    @classmethod
    def show_sections_all(cls):
        config = cls.config_read()
        for s in config.sections():
            print('[%s]' % s)
            for pr in config.options(s):
                print(pr, ' = ', config[s][pr])


if __name__ == '__main__':
    print("""\033[32;1m
    (0) 初始化配置文件
    (1) 增加配置
    (2) 删除配置
    (3) 修改配置
    (4) 查询配置
    (5) 查看所有配置\033[0m
    """)
    while True:
        choose = input('选择操作项 >> ').strip()
        if choose.isdigit():
            choose = int(choose)
            if choose < 5 and choose > 0:
                section = input('sections >> ').strip()
                item = input('item >> ').strip()
                conf = Config(section, item)
                if choose == 1:
                    price = input('add item_price >> ').strip()
                    conf.config_add(price)
                elif choose == 2:
                    conf.config_delete()
                elif choose == 3:
                    price = input('change item_price >> ').strip()
                    conf.config_change(price)
                else:
                    conf.config_select()
            elif choose == 0:
                affirm = input('yes/no ? >> ').strip()
                if affirm == 'yes':
                    Config.config_create()
                    print('\033[32;1m配置文件初始化成功\033[0m')
                else:
                    print('\033[31;1m已取消操作\033[0m')
            elif choose == 5:
                Config.show_sections_all()
            else:
                print('\033[31;1m没有此项目\033[0m')
        else:
            print('\033[31;1m请正确输入\033[0m')

 

posted on 2017-04-18 21:42  奋斗德路  阅读(238)  评论(0编辑  收藏  举报