zoukankan      html  css  js  c++  java
  • Python读写配置文件模块--Configobj

    from configobj import ConfigObj
    import os
    
    
    # Python读写配置文件模块--Configobj
    class TestConfig():
    
        def __init__(self):
            self.path = os.path.dirname(os.path.dirname(__file__)) + "/config/config.ini"
            print(self.path)
            # 实例化一个Configobj对象,给ConfigObj一个配置文件的路径,然后通过字典来访问成员,子段也是一个字典
            self.config = ConfigObj(self.path, encoding='UTF-8')
    
        # 读取配置文件信息
        def query_config(self):
            print(self.config['HJ'])
            print(self.config['HJ']['hj'])
    
        # 给配置文件添加新项
        def add_config(self):
            self.config['data'] = {}
            self.config['data']['user'] = 'root'
            self.config.write()
    
        # 修改配置文件
        def modify_config(self):
            print(self.config['HJ']['hj'])
            self.config['HJ']['hj'] = 'regression'
            self.config.write()
    
            print(self.config['HJ']['hj'])
            self.config['HJ']['hj'] = 'maoyan'
    
            self.config.write()
            print(self.config['HJ']['hj'])
    
        # 删除配置文件中的某个项
        def del_config(self):
            del self.config['data']['user']
            del self.config['data']
            self.config.write()
    
        # 将配置文件写入到不同的文件
        def write_other_file(self):
            self.config.filename = os.path.dirname(os.path.dirname(__file__)) + "/config/test.ini"
            self.config.write()
    
        # 创建一个新配置文件
        def create_new_config(self):
            config = ConfigObj()
    
            config.filename = os.path.dirname(os.path.dirname(__file__)) + "/config/test1.ini"
            config['student'] = {}
            config['student']['name'] = 'Jardon'
            config['student']['age'] = '56'
    
            config.write()
    
    
    if __name__ == '__main__':
        t = TestConfig()
        # t.query_config()
        # t.modify_config()
        # t.add_config()
        # t.del_config()
        # t.write_other_file()
        t.create_new_config()


    作者:Glen.He
    出处:http://www.cnblogs.com/puresoul/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

  • 相关阅读:
    隐藏quick launch(非原创)
    MOSS 的缓存及察看
    在ubantu 8.4上 让鼠标的滚轮工作
    关于QuickHTML的开发 (1)
    Jquery 和 shanrepoint
    一个简单的隐藏quick launch的js方法
    在vmware workstation 6.5上安装 vmware tools
    一本有关 MOSS 开发的书 Wrox.SharePoint.2007.and.Office.Development.Expert.Solutions
    IOS 概述
    iPhone应用程序开发基础之一: IBOutlet与IBAction
  • 原文地址:https://www.cnblogs.com/puresoul/p/14881823.html
Copyright © 2011-2022 走看看