Python ConfigParser模块

ConfigParser 可以用来读取配置文件。是一个内置模块,不需要独立安装

简单读取配置文件示例

  • read(filename) 直接读取文件内容
  • get(section, option) 获取section 下具体某一配置项的值(返回的是字符串)
  • sections() 得到所有的section,并以列表的形式返回
  • options(section) 得到该section的所有option
  • items(section) 键值对的形式 得到该section的所有option
  • getint(section,option)cnf.getboolean(section,option)getfloat(section,option) 获取整型、布尔型和浮点型的option的值

有配置文件set.ini如下:

[mysql]     # section
db_ip = 127.0.0.1
db_port = 3306
db_user = mysql
db_pass = mysql

[redis]     # section
redis_ip = 127.0.0.1
redis_port = 3978
redis_user = redis

read(filename) 直接读取文件内容
In [2]: cnf = ConfigParser.ConfigParser()

In [4]: cnf.read('set.ini')
Out[4]: ['set.ini']
get(section, option) 获取section 下具体某一配置项的值(返回的是字符串)
In [6]: cnf.get('mysql', 'db_port')
Out[6]: '3306'
sections() 得到所有的section,并以列表的形式返回
In [7]: cnf.sections()
Out[7]: ['mysql', 'redis']
options(section) 得到该section的所有option
In [9]: cnf.options('mysql')
Out[9]: ['db_ip', 'db_port', 'db_user', 'db_pass']
items(section) 键值对的形式 得到该section的所有option
In [10]: cnf.items('mysql')
Out[10]:
[('db_ip', '127.0.0.1'),
 ('db_port', '3306'),
 ('db_user', 'mysql'),
 ('db_pass', 'mysql')]
getint(section,option)cnf.getboolean(section,option)getfloat(section,option) 获取整型、布尔型和浮点型的option的值
In [13]: cnf.getint('mysql', 'db_port')
Out[13]: 3306

In [15]: cnf.getfloat('mysql', 'db_port')
Out[15]: 3306.0

简单的写入配置文件示例

  • add_section(section) 添加一个新的section
  • set(section, option, value) 对section中添加 option 和 value
  • remove_section(section) 删除某个 section
  • remove_option(section, option) 删除某个 section 下的 option
  • write() 将设置的新的 section 和 option 写到文件中
add_section(section) 添加一个新的section
In [16]: cnf.add_section('mongo')
set(section, option, value) 对section中添加 option 和 value
In [17]: cnf.set('mongo', 'mongo_ip', '127.0.0.2')

In [18]: cnf.set('mongo', 'mongo_port', 27001)
write() 将设置的新的 section 和 option 写到文件中
In [19]: with open('set.ini', 'w+') as f:
    ...:    cnf.write(f)

# 看文件
$ cat set.ini
...
[mongo]
mongo_ip = 127.0.0.2
mongo_port = 27001
remove_option(section, option) 删除某个 section 下的 option
In [20]: cnf.remove_option('mongo', 'mongo_port')
Out[20]: True

In [21]: with open('set.ini', 'w+') as f:
    ...:    cnf.write(f)

# 看文件
$ cat set.ini
...
[mongo]
mongo_ip = 127.0.0.2
remove_section(section) 删除某个 section
In [22]: cnf.remove_section('mongo')
Out[22]: True

In [23]: with open('set.ini', 'w+') as f:
    ...:    cnf.write(f)


作者:SateZheng
链接:https://www.jianshu.com/p/2f0636e27477
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
posted @ 2020-04-09 19:02  lincappu  阅读(345)  评论(0编辑  收藏  举报