Fork me on GitHub

Python configparser模块

注意:在python 3 中ConfigParser模块名已更名为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)

 

原文链接:https://www.jianshu.com/p/2f0636e27477 


ConfigParser模块在python中用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一个或多个节(section), 每个节可以有多个参数(键=值)。使用的配置文件的好处就是不用在程序员写死,可以使程序更灵活。 

注意:在python 3 中ConfigParser模块名已更名为configparser

configparser函数常用方法:

读取配置文件:

复制代码
 1 read(filename) #读取配置文件,直接读取ini文件内容
 2 
 3 sections() #获取ini文件内所有的section,以列表形式返回['logging', 'mysql']
 4 
 5 options(sections) #获取指定sections下所有options ,以列表形式返回['host', 'port', 'user', 'password']
 6 
 7 items(sections) #获取指定section下所有的键值对,[('host', '127.0.0.1'), ('port', '3306'), ('user', 'root'), ('password', '123456')]
 8 
 9 get(section, option) #获取section中option的值,返回为string类型
10 >>>>>获取指定的section下的option <class 'str'> 127.0.0.1
11 
12 getint(section,option) 返回int类型
13 getfloat(section, option)  返回float类型
14 getboolean(section,option) 返回boolen类型
复制代码

举例如下:

配置文件ini如下:

复制代码
[logging]
level = 20
path =
server =

[mysql]
host=127.0.0.1
port=3306
user=root
password=123456
复制代码

注意,也可以使用:替换=

代码如下:

复制代码
import configparser
from until.file_system import get_init_path

conf = configparser.ConfigParser()
file_path = get_init_path()
print('file_path :',file_path)
conf.read(file_path)

sections = conf.sections()
print('获取配置文件所有的section', sections)

options = conf.options('mysql')
print('获取指定section下所有option', options)


items = conf.items('mysql')
print('获取指定section下所有的键值对', items)


value = conf.get('mysql', 'host')
print('获取指定的section下的option', type(value), value)
复制代码

运行结果如下:

file_path : /Users/xxx/Desktop/xxx/xxx/xxx.ini
获取配置文件所有的section ['logging', 'mysql']
获取指定section下所有option ['host', 'port', 'user', 'password']
获取指定section下所有的键值对 [('host', '127.0.0.1'), ('port', '3306'), ('user', 'root'), ('password', '123456')]
获取指定的section下的option <class 'str'> 127.0.0.1

 

综合使用方法:

复制代码
import configparser
"""
读取配置文件信息
"""

class ConfigParser():

    config_dic = {}
    @classmethod
    def get_config(cls, sector, item):
        value = None
        try:
            value = cls.config_dic[sector][item]
        except KeyError:
            cf = configparser.ConfigParser()
            cf.read('settings.ini', encoding='utf8')  #注意setting.ini配置文件的路径
            value = cf.get(sector, item)
            cls.config_dic = value
        finally:
            return value


if __name__ == '__main__':
    con = ConfigParser()
    res = con.get_config('logging', 'level')
    print(res)
复制代码

 

参考链接:

http://blog.csdn.net/henulwj/article/details/49174355

原文链接:

https://www.cnblogs.com/lhly/p/8066898.html

posted @ 2020-12-15 16:15  stardsd  阅读(323)  评论(0编辑  收藏  举报