configparser 的介绍
configparser 包是 Python3 内置的包,可以很方便的读写配置文件。
配置文件格式
配置文件中包含一个或多个 section, 每个 section 有自己的 option;
section 用 [sect_name] 表示,每个 option 是一个键值对,使用分隔符 = 或 : 隔开;
在 option 分隔符两端的空格会被忽略掉
配置文件使用 # 和 ; 注释
1 2 3 4 5 6 7 8 9 10 11 12 13
| [db] db_port = 3306 db_user = root db_host = 127.0.0.1 db_pass = xgmtest test_float = 1.1 test_bool = True
[concurrent] processor = 20 thread = 10
|
通过 configparser 读取示例的配置文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| import configparser
con = configparser.ConfigParser()
con.read('config.conf', encoding='utf8')
print('该配置文件所有的section为:{},类型为:{}'.format(con.sections(), type(con.sections())))
print('section"{}"中所有的option和值为:{},类型为:{}'.format('db', con.items('db'), type(con.items('db'))))
print('section"{}"中"{}"的值为:{},类型为:{}'.format('db', 'db_pass', con.get('db','db_pass'), type(con.get('db','db_pass'))))
print('section"{}"中"{}"的值为:{},类型为:{}'.format('db', 'db_port', con.getint('db', 'db_port'),type(con.getint('db', 'db_port'))))
print('section"{}"中"{}"的值为:{},类型为:{}'.format('db', 'test_float', con.getfloat('db', 'test_float'),type(con.getfloat('db', 'test_float'))))
print('section"{}"中"{}"的值为:{},类型为:{}'.format('db', 'test_bool', con.getboolean('db', 'test_bool'),type(con.getboolean('db', 'test_bool'))))
|
上述代码输出结果为:
1 2 3 4 5 6
| 该配置文件所有的section为:['db', 'concurrent'],类型为:<class 'list'> section"db"中所有的option和值为:[('db_port', '3306'), ('db_user', 'root'), ('db_host', '127.0.0.1#测试'), ('db_pass', 'xgmtest'), ('test_float', '1.1'), ('test_bool', 'True')],类型为:<class 'list'> section"db"中"db_pass"的值为:xgmtest,类型为:<class 'str'> section"db"中"db_port"的值为:3306,类型为:<class 'int'> section"db"中"test_float"的值为:1.1,类型为:<class 'float'> section"db"中"test_bool"的值为:True,类型为:<class 'bool'>
|
通过 configparser 将配置写入到配置文件中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| con = configparser.ConfigParser()
con.add_section('db') con.add_section('test')
con.set('db', 'db_pass', '123456') con.set('db', 'dbb', '123') con.set('test', 'test_int', '123') con.set('test', 'test_float', '1.1') con.set('test', 'test_bool', 'True')
con.remove_option('db', 'dbb')
con.remove_section('db') with open('config_write.conf', 'w+') as f: con.write(f)
|
执行之后配置文件 config_write.conf 中的内容为:
1 2 3 4 5 6 7 8
| [db] db_pass = 123456 dbb = 123
[test] test_int = 123 test_float = 1.1 test_bool = True
|
如果取消两行 remove 的注释的话,执行之后配置文件 config_write.conf 中的内容为:
1 2 3 4
| [test] test_int = 123 test_float = 1.1 test_bool = True
|
参考链接:
https://www.cnblogs.com/feeland/p/4514771.html
https://www.cnblogs.com/wang-yc/p/5620944.html
本文章首发于个人博客 LLLibra146’s blog
本文作者:LLLibra146
更多文章请关注公众号 (LLLibra146):![LLLibra146]()
版权声明:本博客所有文章除特别声明外,均采用 © BY-NC-ND 许可协议。非商用转载请注明出处!严禁商业转载!
本文链接:
https://blog.d77.xyz/archives/c8f31e5f.html