python 解析 配置文件

时间:2023-03-09 03:21:16
python 解析 配置文件

资料: https://docs.python.org/3/library/configparser.html

环境

python 3.4.4

RawConfigParser方式

example.cfg文件:

[Section1]
an_int =
a_bool = true
a_float = 3.1415
baz = fun
bar = Python
foo = %(bar)s is %(baz)s!

test_example_ini.py 文件:

import configparser

def test_write():
config = configparser.RawConfigParser()
config.add_section('Section1')
config.set('Section1', 'an_int', '')
config.set('Section1', 'a_bool', 'true')
config.set('Section1', 'a_float', '3.1415')
config.set('Section1', 'baz', 'fun')
config.set('Section1', 'bar', 'Python')
config.set('Section1', 'foo', '%(bar)s is %(baz)s!') with open('example.cfg', 'w',encoding="utf-8") as configfile:
config.write(configfile) def test_read():
config = configparser.RawConfigParser()
config.read('example.cfg') a_float = config.getfloat('Section1', 'a_float')
an_int = config.getint('Section1', 'an_int')
print (a_float + an_int) if config.getboolean('Section1', 'a_bool'):
print (config.get('Section1', 'foo')) if __name__=="__main__":
test_write()
test_read()

输出:

18.1415
%(bar)s is %(baz)s!

同时生成example.cfg文件,内容如下:

[Section1]
an_int = 15
a_bool = true
a_float = 3.1415
baz = fun
bar = Python
foo = %(bar)s is %(baz)s!

ConfigParser方式

mysql.cfg 文件内容:

[mysqld]
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
skip-external-locking = True
old_passwords = 1
skip-bdb = True
skip-innodb = False [oracle]
user = root
password = hello

test_mysql_cfg.py 文件内容:

import configparser

def test_write():
config = configparser.ConfigParser()
config.read('mysql.cfg') config.set("mysqld", "mysql_pass", "")
config.write(open('mysql.cfg', "w")) def test_read():
config = configparser.ConfigParser()
config.read('mysql.cfg') s = config.sections()
print ('section:', s) o = config.options("mysqld")
print ('mysqld:', o) v = config.items("mysqld")
print ('mysql:', v) mysql_user = config.get("mysqld", "user")
mysql_pid = config.get("mysqld", "pid-file")
mysql_old = config.getint("mysqld", "old_passwords")
mysql_skipbdb = config.get("mysqld", "skip-bdb") print (mysql_user, mysql_pid, mysql_old, mysql_skipbdb) if __name__=="__main__":
test_write()
test_read()

执行结果:

section: ['mysqld', 'oracle']
mysqld: ['user', 'pid-file', 'skip-external-locking', 'old_passwords', 'skip-bdb', 'skip-innodb', 'mysql_pass']
mysql: [('user', 'mysql'), ('pid-file', '/var/run/mysqld/mysqld.pid'), ('skip-external-locking', 'True'), ('old_passwords', ''), ('skip-bdb', 'True'), ('skip-i
nnodb', 'False'), ('mysql_pass', '123456')]
mysql /var/run/mysqld/mysqld.pid 1 True

同时mysql.cfg变化如下:

[mysqld]
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
skip-external-locking = True
old_passwords = 1
skip-bdb = True
skip-innodb = False
mysql_pass = 123456 [oracle]
user = root
password = hello