python对ini配置文件处理

转载自
https://www.cnblogs.com/wxl-dede/p/4998840.html

test.ini


[base]

host = 192.168.88.121

port = 3306

user = root

path = /home

passwd = 123

[callback]

path = /Autops

alert = yes

count = 1

ftp = no
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 19 09:48:00 2018

@author: linzhiwei02
"""

import configparser
cf = configparser.ConfigParser()    #创建对象
cf.read('test_ini.ini')     #读取ini配置文件
print("读取所有节")
print (cf.sections())   

print ("配置key值/配置项")
print (cf.options("base"))

print ("配置选项和值")
print (cf.items("base"))

print("获取 base port 的值")
print(cf.get("base","port"))


cf.set("base","passwd","123")   

cf.write(open("test_ini.ini","w"))    

print (cf.getint('base','port'))   

print(cf.getfloat('base','port'))

print (cf.getboolean('callback','alert')) #0/no/false/off都视为False

print(cf.getboolean('callback','count'))

读取所有节
['base', 'callback']
配置key值/配置项
['host', 'port', 'user', 'path', 'passwd']
配置选项和值
[('host', '192.168.88.121'), ('port', '3306'), ('user', 'root'), ('path', '/home'), ('passwd', '123')]
获取 base port 的值
3306
3306
3306.0
True
True

当配置文件中有定义DEFAULT片段时,在其他片段中找不到的相应的key时,就会到DEFAULT中去查找,如果还是没有就会报错NoOptionError

[DEFAULT]

dbn=mysql

user=root

[base]

user = autops

>>> cf.get('base','user')

'autops'

>>> cf.get('base','dbn')

'mysql                                                      #dbn的值是default里的

可以像字符串进行变量替换,形成一个大字符串 %s

[DEFAULT]

conn_str=%(dbn)s -u%(user)s -p%(passwd)s %(db)s

dbn=mysql

user=root

host = 192.168.88.121

port = 3306

[db1]

port = 3307

user = root

db = autops

passwd = 123

[db2]

user = monitor

db = monitor

passwd = 123
>>> cf.get("db1","conn_str")

'mysql -uroot -p123 autops'

>>> cf.get("db2","conn_str")

'mysql -umonitor -p123 monitor

猜你喜欢

转载自blog.csdn.net/csdn_lzw/article/details/81110501