configparser Python配置文件ini解析器

configparser简介

configparser,Python中的一个可以用于解析配置文件的标准库。可以使用该模块来设计编写最终由用户自己来定义的Python程序。

configparser应用实例

如何创建下方这样的一个配置文件:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[forge.example]
User = hg

[topsecret.server.example]
Port = 50022
ForwardX11 = no

可以使用Python的configparser标准库:

import configparser
config = configparser.ConfigParser()
config['DEFAULT'] = {'ServerAliveInterval': '45',
                     'Compression': 'yes',
                     'CompressionLevel': '9'}
config['forge.example'] = {}
config['forge.example']['User'] = 'hg'
config['topsecret.server.example'] = {}
topsecret = config['topsecret.server.example']
topsecret['Port'] = '50022'     # mutates the parser
topsecret['ForwardX11'] = 'no'  # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
  config.write(configfile)

读取ini配置文件中的数据:

config = configparser.ConfigParser()
config.sections()
[]
config.read('example.ini')
['example.ini']
config.sections()
['forge.example', 'topsecret.server.example']
'forge.example' in config
True

免责声明:内容编辑自网络,仅供参考,不保证正确性,不作任何决策依据!!以上数据皆截止于博文的写稿日期。


行业导航 / Python指南 :
























Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.