Python 基础

configparser模块介绍

用于生成和修改常见的配置文档(configuration file)。 配置文档主要包括 ini, cfg, xml, config等

 Python的ConfigParser Module中定义了3个类对INI文件进行操作。分别是RawConfigParser、ConfigParser、SafeConfigParser。一般使用 configparser.ConfigParser。 ConfigParser类比RawConfigParser多几个接口, ConfigParser、SafeConfigParser支持对%(value)s变量的解析。

模块所解析的ini配置文件是由多个section构成,每个section名用中括号‘[]’包含,每个section下可有多个配置项类似于key-value形式,

配置文件格式

用户配置文件就是在用户登录电脑时,或是用户在使用软件时,软件系统为用户所要加载所需环境的设置和文件的集合。它包括所有用户专用的配置设置,如程序项目、屏幕颜色网络连接、打印机连接、鼠标设置及窗口的大小和位置等。一般格式包括ini,cfg,xml, config等。

配置文件包括一个或者多个sections, section以 [ 和 ] 里的内容命名。 在section下的称为options。options 包括names 和 values, 以 = 或者: 分割。 配置文件的格式如下

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
 
[bitbucket.org]
User = hg
 
[topsecret.server.com]
Port = 50022
ForwardX11 = no

sections 包括 DEFAULT, bitbucket.org, 和topsecret.server.com 。 DEFAULT 下由4 个options

或者 s

# This is a simple example with comments.
[bug_tracker]
url = http://localhost:8080/bugs/
username = dhellmann
; You should not store passwords in plain text
; configuration files.
password = SECRET

常用操作

生成配置文件

import configparser

config = configparser.ConfigParser()

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

config['bitbucket.org'] = {}  # node 2
config['bitbucket.org']['User'] = 'hg'

config['topsecret.server.com'] ={}  # node 3
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022'
topsecret['FowardXll'] = 'yes'

with open('example.ini','w') as configfile:
    config.write(configfile)
生成配置文件

读取配置文件: ConfigParser类下

read(filename) 直接读取ini文件内容

-sections() 得到所有的section,并以列表的形式返回

-options(section) 得到该section的所有option

-items(section) 得到该section的所有键值对

-get(section,option) 得到section中option的值,返回为string类型

-getint(section,option) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。

import configparser

conf = configparser.ConfigParser()

conf.read("example.ini")

print(conf.sections())  # 返回只打印节点,DEFAULT不打印

print(conf.defaults()) # 打印default内容

print(conf["bitbucket.org"]["user"])
初始化和读取,和字典差不多

增加写入配置文件

add_section(section) 添加一个新的section

set( section, option, value) 对section中的option进行设置,需要调用write将内容写入配置文件。

write(strout) 将对configparser类的修改写入

原文地址:https://www.cnblogs.com/lg100lg100/p/7414284.html