Python的configparser读写配置文件
Posted zhangphil
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python的configparser读写配置文件相关的知识,希望对你有一定的参考价值。
Python的configparser读写配置文件
假设配置文件为config.ini,里面原有的配置项内容为:
[kafak.server] host = 99.99.99.99 port = 80 [zookeeper.server] host = 100.100.100.100 port = 2181 [local] client.port = 0 name = null
python读写更改config.ini里面的配置项:
import configparser as cfp
if __name__ == '__main__':
my_cfg = "./config.ini"
config = cfp.ConfigParser()
config.read(my_cfg)
# 读取配置
secs = config.sections()
print(secs)
print(config.options('kafak.server'))
items = config.items('kafak.server')
print(items)
print(config.get('kafak.server', 'host'))
print(config.get('kafak.server', 'port'))
print(config.options('zookeeper.server'))
items = config.items('zookeeper.server')
print(items)
print(config.get('zookeeper.server', 'host'))
print(config.get('zookeeper.server', 'port'))
# 写配置,更新配置
config.set('local', 'client.port', '12345')
config.set('local', 'name', 'zhangphil')
f = open(my_cfg, 'w')
config.write(f)
f.close()
输出:
['kafak.server', 'zookeeper.server', 'local']
['host', 'port']
[('host', '99.99.99.99'), ('port', '80')]
99.99.99.99
80
['host', 'port']
[('host', '100.100.100.100'), ('port', '2181')]
100.100.100.100
2181
修改后的config.ini配置内容:
[kafak.server] host = 99.99.99.99 port = 80 [zookeeper.server] host = 100.100.100.100 port = 2181 [local] client.port = 12345 name = zhangphil
以上是关于Python的configparser读写配置文件的主要内容,如果未能解决你的问题,请参考以下文章