python configparser模块
ConfigParser模块在python中用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一个或多个节(section), 每个节可以有多个参数(键=值)。使用的配置文件的好处就是不用在程序员写死,可以使程序更灵活。
注意:在python 3 中ConfigParser
模块名已更名为configparser
configparser函数常用方法:
读取配置文件:
[](javascript:void(0)😉
1 read(filename) #读取配置文件,直接读取ini文件内容 2 3 sections() #获取ini文件内所有的section,以列表形式返回['logging', 'mysql'] 4 5 options(sections) #获取指定sections下所有options ,以列表形式返回['host', 'port', 'user', 'password'] 6 7 items(sections) #获取指定section下所有的键值对,[('host', '127.0.0.1'), ('port', '3306'), ('user', 'root'), ('password', '123456')] 8 9 get(section, option) #获取section中option的值,返回为string类型 10 >>>>>获取指定的section下的option <class 'str'> 127.0.0.1 11 12 getint(section,option) 返回int类型 13 getfloat(section, option) 返回float类型 14 getboolean(section,option) 返回boolen类型
[](javascript:void(0)😉
举例如下:
配置文件ini如下:
[](javascript:void(0)😉
[logging] level = 20 path = server = [mysql] host=127.0.0.1 port=3306 user=root password=123456
[](javascript:void(0)😉
注意,也可以使用:替换=
代码如下:
[](javascript:void(0)😉
import configparser from until.file_system import get_init_path conf = configparser.ConfigParser() file_path = get_init_path() print('file_path :',file_path) conf.read(file_path) sections = conf.sections() print('获取配置文件所有的section', sections) options = conf.options('mysql') print('获取指定section下所有option', options) items = conf.items('mysql') print('获取指定section下所有的键值对', items) value = conf.get('mysql', 'host') print('获取指定的section下的option', type(value), value)
[](javascript:void(0)😉
运行结果如下:
file_path : /Users/xxx/Desktop/xxx/xxx/xxx.ini 获取配置文件所有的section ['logging', 'mysql'] 获取指定section下所有option ['host', 'port', 'user', 'password'] 获取指定section下所有的键值对 [('host', '127.0.0.1'), ('port', '3306'), ('user', 'root'), ('password', '123456')] 获取指定的section下的option <class 'str'> 127.0.0.1
综合使用方法:
[](javascript:void(0)😉
import configparser """ 读取配置文件信息 """ class ConfigParser(): config_dic = {} @classmethod def get_config(cls, sector, item): value = None try: value = cls.config_dic[sector][item] except KeyError: cf = configparser.ConfigParser() cf.read('settings.ini', encoding='utf8') #注意setting.ini配置文件的路径 value = cf.get(sector, item) cls.config_dic = value finally: return value if __name__ == '__main__': con = ConfigParser() res = con.get_config('logging', 'level') print(res)
[](javascript:void(0)😉
参考链接:
http://blog.csdn.net/henulwj/article/details/49174355
后续补充~~~~
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!