configparser模块
功能:用于生成和修改常见配置文件。
基本常用方法如下:

read(filename):直接读取配置文件
write(filename):将修改后的配置文件写入文件中。
defaults():返回全部示例中所有defaults
sections():得到所有的section,并以列表的形式返回
items(section):得到该section的所有键值对
has_section(section):检查是否有section,有返回True,无返回False
has_option(section,option):检查section下是否有指定的option,有返回True,无返回False
getint(section,option):得到section中option的值,返回为int类型
get(section,option):得到section中option的值,返回为string类型
getboolean(section,option):得到section中option的值,返回为boolean类型
getfloat(section,option):得到section中option的值,返回为float类型
add_section(section):添加一个新的section
remove_section(section):删除某个section
options(section):得到该section的所有option
set(section,option,value):对section中的option进行设置,需要调用write将内容写入配置文件
remove_option(section,option):删除某个section下的option


能处理的配置文件格式如下:
[mysql] #节点名
键 = 值
举例1:自动生成一个配置文件
 1 import configparser
 2 # 自动生成配置文件
 3 cfg = configparser.ConfigParser()
 4 # 创建一个全局配置
 5 cfg['DEFAULT'] = {
 6     'ServerAliveInterval':'45',
 7     'Compression':'yes',
 8     'CompressionLevel':'9'
 9 }
10 #创建局部配置
11 cfg['bitbucket.org'] = {}
12 cfg['bitbucket.org']['User'] = 'hg'
13 cfg['topsecret.server.com'] = {}
14 topsecret = cfg['topsecret.server.com']
15 topsecret['host port'] = '50022'
16 topsecret['ForwardX11'] = 'no'
17 cfg['DEFAULT']['ForwardX11'] = 'yes'
18 # 配置完成,重写文件
19 with open('example.ini','w') as f:
20     cfg.write(f)
View Code

相关文章:

  • 2022-03-03
  • 2021-10-10
  • 2021-12-04
  • 2022-02-15
  • 2022-03-06
猜你喜欢
  • 2021-06-16
  • 2021-09-10
  • 2021-08-23
  • 2021-09-04
  • 2021-08-08
  • 2021-09-09
相关资源
相似解决方案