python configparser.RawConfigParser.read(filenames,encoding='utf8'))讀取配置文件列表

configparser在讀取配置文件時,有四種方法:read(filenames, encoding=None)讀取文件列表,也可以讀取單個文件;read_file(f, source=None) 讀取單個文件;read_string(string, source=’’) 讀取字符串;read_dict(dictionary, source=’’)讀取字典。

read_file(f, source=None)替換了原來的readfp()方法。

1、準備配置文件,配置文件依舊使用上一篇中的mysql.ini文件,同時新增一個sql.ini文件。

mysql.ini文件
[MySQLdb]
user = dev
passwd = ‘dev’
db = ‘jellyfish_user’
host = ‘192.168.16.176’
port = 3306
charset = ‘utf8’
maxconnect = 5
[db]
user = ming
passwd = user_4_script
db = jellyfish_user
host = 112.62.16.81
port = 1
charset = utf8
maxconnect = 5

sql.ini文件
[db]
user=dev
passwd=‘dev’
db=‘jellyfish_user’
host=‘192.168.16.176’
port=3306
charset=‘utf8’
maxconnect=5
[MySQLdb]
user=script_user
passwd=user_4_script
db=jellyfish_user
host=112.62.16.81
port=1
charset=utf8
maxconnect=5
[test]
name=wang

2、使用read(filenames, encoding=None)讀取數據。

# coding:utf-8
'''
Note:
   讀取配置文件
Author:Qred
Date:2019/8/27
'''

import configparser

def main():
   path = [ 'mysql.ini', 'sql.ini' ]
   cfg = configparser.RawConfigParser()

   print '打印讀取的配置文件列表'
   print cfg.read(path)
   print '打印從配置文件讀取到的所有sections節點'
   print cfg.sections()
   print '不同配置文件有相同的section節點,後讀取到的節點會覆蓋之前的節點數據'
   print cfg.items('db')
   
if __name__ == '__main__':
    main()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章