Python 读写配置文件

很多时候我们需要在程序代码中建立配置文件存储DB及其它配置信息。这时就需要去获取配置文件中的关键数据。

使用模块:ConfigParser

 

1.读取配置文件

样例配置文件:dserver.conf

[root@localhost conf]# cat dserver.conf 
[rabbitmq]
RABBIT_HOST = 192.168.175.130
RABBIT_USERNAME = dockerm
RABBIT_PASSWORD = 123456
RABBIT_PORT = 5672
RABBIT_VHOST = dockerm_vhost

[mysqld]
MYSQL_HOST = 127.0.0.1
MYSQL_USERNAME = dmserver
MYSQL_PASSWORD = 123456
MYSQL_PORT = 3306
MYSQL_DB = dcenter
[root@localhost conf]# 

 

读取文件方法

1.导入模块

2.实例化对象

3.读入文件

4.获取section关键内容信息

5.获取具体配置信息

 

用法:

[root@localhost conf]# ipython
Python 2.7.5 (default, Nov  6 2016, 00:28:07) 
Type "copyright", "credits" or "license" for more information.

IPython 5.2.2 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

#导入模块
In [1]: import ConfigParser

#实例化对象
In [2]: config = ConfigParser.ConfigParser()

#指定读入的文件
In [3]: config.read('dserver.conf')
Out[3]: ['dserver.conf']

#获取文件中有哪些部分
In [4]: config.sections()
Out[4]: ['rabbitmq', 'mysqld']

#获取指定关键部分名的具体选项配置
In [5]: config.options('rabbitmq')
Out[5]: 
['rabbit_host',
 'rabbit_username',
 'rabbit_password',
 'rabbit_port',
 'rabbit_vhost']
#获得指定section的所有内容
In [6]: config.items('rabbitmq')
Out[6]: 
[('rabbit_host', '192.168.175.130'),
 ('rabbit_username', 'dockerm'),
 ('rabbit_password', '123456'),
 ('rabbit_port', '5672'),
 ('rabbit_vhost', 'dockerm_vhost')]
#获取指定选项的内容String类型
In [7]: config.get('rabbitmq','rabbit_port')
Out[7]: '5672'
#获取指定选项的内容 int类型
In [8]: config.getint('rabbitmq','rabbit_port')
Out[8]: 5672

In [9]: 

2.写配置

1.导入模块

2.实例化对象

3.读入文件

4.写入配置

5.保存内容

 

#添加option配置信息,如果存在就修改
In [9]: config.set("rabbitmq","Test","123456")
#添加新的section
In [10]: config.add_section('API')
#添加新的option到指定的section
In [11]: config.set('API','url','http://www.baidu.com/api')
#保存配置
In [12]: config.write(open("dserver.conf","w"))

 

 

检查写入信息

 

[root@localhost dserver]# cat conf/dserver.conf 
[rabbitmq]
rabbit_host = 192.168.175.130
rabbit_username = dockerm
rabbit_password = 123456
rabbit_port = 5672
rabbit_vhost = dockerm_vhost
test = 123456

[mysqld]
mysql_host = 127.0.0.1
mysql_username = dmserver
mysql_password = 123456
mysql_port = 3306
mysql_db = dcenter

[API]
url = http://www.baidu.com/api