内置模块之configparser

configparser模块

  configparser模块用来操作配置文件(.ini格式),这种格式的配置文件,包含多个组section,每个组可以包含多个键值对option,目前.ini这种格式的配置文件已经逐渐的不流行了。

  ##############################################

  配置文件的思想:

   # 当你把你本机的整个程序都拷贝到其他机器上,无论相对路径/相对路径都不靠谱,因为别的机器上的环境不一定与你的开发环境一直,然后其他操作人员又不一定懂开发,此时就需要配置文件了,把这些都放在一个配置文件中,让其他人员也能修改,从而保证程序的正常运行。

  ##############################################

  configparser:

    (1) 格式约束十分严格,必须把配置项都放置到一个section中,忽略大小写。

    (2) DEFAULT组是一个十分特殊的组,它属于所有组,在其他组里面都可以覆盖其配置项,也可以在其他组里取到DEFAULT的任何一个配置项。类似于父类与子类的感觉。


configparser模块的使用

  下面有一个现成的.ini格式的配置文件:

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

  如何使用configeparser模块生成一个这样的.ini文件

import configparser
#(1) 实例化得到一个config对象
config = configparser.ConfigParser()
#(2)对象[section名] = {key1:value1,key2:value2}进行在section中添加section
config['DEFAULT'] = {
    'ServerAliveInterval': '45',
    'Compression': 'yes',
}

config['bitbucket.org'] = {
    'User':'hg'
}

config['topsecret.server.com'] = {
    'Host Port': '50022',
    'password' : 'xxxxx'
}
#(3)打开一个配置文件,把内容写入。
with open('config.ini','w') as f:
    config.write(f)

  学会了生成配置文件,那么该如何查找配置文件的option。

#(1)先实例化出来一个对象
config = configparser.ConfigParser()

# (2)把配置文件中的所有内存读进来
config.read('config.ini')

#(3)基于字典的形式查询
print(config['topsecret.server.com']['Host Port'])
>>>
50022

# (4) 在任意一个组都可以查询到DEFAULT组的任意option
print(config['topsecret.server.com']['compression'])
>>>
yes

#(5) 既然是基于字典的形式,那么肯定也可以通过for循环来查询
# 默认都会把DEFAULT组中的所有key都打印出来
for key in config['topsecret.server.com']:
    print(key)
>>>
host port
password
serveraliveinterval
compression

#(6)获取组下面的键值对,通过"对象名.items('section')"
print(config.items('topsecret.server.com'))
>>>
[('serveraliveinterval', '45'), ('compression', 'yes'), ('host port', '50022'), 
('password', 'xxxxx')]

  学会了创建,查询,接下来学习如果增删改配置项

# 增删改
config = configparser.ConfigParser()

config.read('config.ini')

# 增加section
config.add_section('mysection')
# 删除原有section
config.remove_section('bitbucket.org')

# 在section中增加新的option
config['mysection']['name'] = 'hehehe'
# 在section中删除option
config.remove_option('topsecret.server.com','password')

#更改option
config.set('topsecret.server.com','host port','8086')

#保存文件
config.write(open('new_config.ini','w'))

  

原文地址:https://www.cnblogs.com/hebbhao/p/9600095.html