打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Python配置文件解析configparser
userphoto

2023.11.03 甘肃

关注

写一个程序的时候有些内容需要动态调整

这些可以动态改变的值,可以放在一个单独的配置文件中,这样程序代码不需要变化,只需要调整配置文件中的值即可。

Python ConfigParser

ConfigParser是一个 Python 类,为 Python 程序实现基本的配置语言。 它提供类似于 Microsoft Windows INI 文件的结构

  • 配置文件由各部分组成,后跟选项的键/值对。
  • 段名用[]字符分隔。 这些对用:=隔开。 注释以#;开头。
[DEFAULT]ServerAliveInterval = 45Compression = yesCompressionLevel = 9ForwardX11 = yes[bitbucket.org]User = hg[topsecret.server.com]Port = 50022ForwardX11 = no
  • [DEFAULT]表示一段配置
  • ServerAliveInterval = 45表示一个key-value的配置
[DEFAULT]ServerAliveInterval = 45Compression = yesCompressionLevel = 9ForwardX11 = yes
  • 如何取到 ServerAliveInterval对应的值45?
import configparserconfig = configparser.ConfigParser()config.read('my.ini')DEFAULT = config['DEFAULT'] print(DEFAULT, )a = DEFAULT['ServerAliveInterval']print(a)

其实你可以理解为这样的结构 config['DEFAULT']的值是一个字典,代码下面的配置信息

config['DEFAULT'] = {'ServerAliveInterval': '45',...                              'Compression': 'yes',...                              'CompressionLevel': '9'}

获取所有的段

卷面我们知道用中括号饭团的一行为一个段[DEFAULT],如何获取所有的这样的段

sections = config.sections()
import configparserconfig = configparser.ConfigParser()config.read('my.ini') sections = config.sections()print(f'Sections: {sections}')
Sections: ['bitbucket.org', 'topsecret.server.com']
  • 输出中少了一个DEFAULT段,实际上这个是默认的段。

把这个段的修改修为 DEFAULT-1 就可以获取所有的段名了

[DEFAULT-1]ServerAliveInterval = 45Compression = yesCompressionLevel = 9ForwardX11 = yes[bitbucket.org]User = hg[topsecret.server.com]Port = 50022ForwardX11 = no
Sections: ['DEFAULT-1', 'bitbucket.org', 'topsecret.server.com']

使用字典代码ini文件

从上面的结构我们可以发现其实这个ini文件和字典结构很类似

可以使用read_dict来从字典中解析配置

cfg_data = {    'DEFAULT': { 'ServerAliveInterval': '45',                 'Compression'        : 'yes',                 'CompressionLevel'   : '9',                 'ForwardX11'         : 'yes'                },         'bitbucket.org': {'User': 'hg'} ,          'topsecret.server.com':                 {                     'Port'       : '50022',                     'ForwardX11' : 'no',                  },}config = configparser.ConfigParser()config.read_dict(cfg_data)print(config)sections = config.sections()print(f'Sections: {sections}')
config.read_dict(cfg_data)

通过程序添加新的配置项

  • add_section添加一个段
  • 然后加入配置项
  • 最后写入文件
config = configparser.ConfigParser()config.add_section('NEW-CONFIG')config['NEW-CONFIG']['host'] = 'localhost'config['NEW-CONFIG']['user'] = 'user7'config['NEW-CONFIG']['passwd'] = 's$cret'config['NEW-CONFIG']['db'] = 'ydb'with open('my.ini', 'a') as configfile:    config.write(configfile)

可以看到新增加了一个段和配置项[NEW-CONFIG],注意里面的换行问题

[DEFAULT]ServerAliveInterval = 45Compression = yesCompressionLevel = 9ForwardX11 = yes[bitbucket.org]User = hg[topsecret.server.com]Port = 50022ForwardX11 = no[NEW-CONFIG]host = localhostuser = user7passwd = s$cretdb = ydb

ini文件中的一些技巧

下面的配置文件,目录,文件名 最后一个是完整的文件路径 是人家两个配置计算出来的

%(users_dir)s\%(name)s表示使用 users_dir和 name这两个配置的值拼接起来的

请注意,“ s”字符是语法的一部分。

my.ini配置文件内容

[info]users_dir= C:\Usersname= Janohome_dir= %(users_dir)s\%(name)s
home_dir = config['info']['home_dir']print(home_dir)
Sections: ['bitbucket.org', 'topsecret.server.com', 'NEW-CONFIG', 'info']C:\Users\Jano
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
python 操作ini 配置文件大全
Python3中的configparser模块
Python3 中 configparser 模块解析配置的用法详解
python读写ini格式的配置文件
Python配置文件模块埋个坑,险些影响了版本上线!
Python 操作 ini文件
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服