Python读写配置文件模块--Configobj
2021/6/14 12:24:57
本文主要是介绍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()
这篇关于Python读写配置文件模块--Configobj的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-18初探Python股票自动化交易:入门指南
- 2024-09-18Python量化入门:轻松掌握量化分析基础与实战
- 2024-09-18Python量化交易:入门指南与实践
- 2024-09-18Python量化交易:入门指南与实战技巧
- 2024-09-14Python人工智能项目实战:从零开始的实践指南
- 2024-09-14探索Python人工智能资料:初学者的指南
- 2024-09-14Python人工智能资料:初学者的全面指南
- 2024-09-13Matplotlib入门:轻松绘制Python数据可视化图表
- 2024-09-13Python人工智能:初学者的入门指南
- 2024-09-13Python人工智能:轻松入门与实践