onfigparser和ConfigParser在python中用来读取ini类型的配置文件的,提供很多方便的API来使用。
#-*-encoding=utf-8-*-
# 测试ConfigParser
import os
import ConfigParser
# 初始化
conf = ConfigParser.ConfigParser()
# 配置文件的绝对路径
conf_path = os.path.dirname(os.path.realpath(__file__)) + "/config.ini"
print(conf_path)
# 读取配置文件
conf.read(conf_path)
"""
读取配置信息
"""
# 查看配置中的所有section
sections = conf.sections()
# print sections
# 返回所有section和序列
sub_conf = conf.options("DOCKER")
print sub_conf
# 返回section中option的值
value_sub_conf = conf.get("DOCKER", "sit")
print value_sub_conf
1、config=ConfigParser.ConfigParser()
创建ConfigParser实例
2、config.sections()
返回配置文件中节序列
3、config.options(section)
返回某个项目中的所有键的序列
4、config.get(section,option)
返回section节中,option的键值
5、config.add_section(str)
添加一个配置文件节点(str)
6、config.set(section,option,val)
设置section节点中,键名为option的值(val)
7、config.read(filename)
读取配置文件
8、config.write(obj_file)
写入配置文件
#coding=utf-8
import ConfigParser
def writeConfig(filename):
config = ConfigParser.ConfigParser()
# set db
section_name = 'db'
config.add_section( section_name )
config.set( section_name, 'dbname', 'MySQL')
config.set( section_name, 'host', '127.0.0.1')
config.set( section_name, 'port', '80')
config.set( section_name, 'password', '123456')
config.set( section_name, 'databasename', 'test')
# set app
section_name = 'app'
config.add_section( section_name )
config.set( section_name, 'loggerapp', '192.168.20.2')
config.set( section_name, 'reportapp', '192.168.20.3')
# write to file
config.write( open(filename, 'a') )
def updateConfig(filename, section, **keyv):
config = ConfigParser.ConfigParser()
config.read(filename)
print config.sections()
for section in config.sections():
print "[",section,"]"
items = config.items(section)
for item in items:
print "\t",item[0]," = ",item[1]
print config.has_option("dbname", "MySQL")
print config.set("db", "dbname", "11")
print "..............."
for key in keyv:
print "\t",key," = ", keyv[key]
config.write( open(filename, 'r+') )
if __name__ == '__main__':
file_name = 'test.ini'
writeConfig(file_name)
updateConfig(file_name, 'app', reportapp = '192.168.100.100')
print "end__"
本文实例讲述了Python读写ini文件的方法。分享给大家供大家参考。具体如下:
比如有一个文件update.ini,里面有这些内容:
1 2 3 4 5 6 7 8 |
|
那就可以通过下面这些代码得到MD5的值,简单吧
1 2 3 4 5 6 7 |
|
写也很简单:
1 2 3 4 5 6 7 8 9 10 |
|
修改也不难(添加内容):
1 2 3 4 5 6 7 8 |
|
修改内容:
1 2 3 4 5 6 7 |
|
删除部分可以看文档
remove_option( section, option)
Remove the specified option from the specified section. If the section does not exist, raise NoSectionError. If the option existed to be removed, return True; otherwise return False. New in version 1.6.
remove_section( section)
Remove the specified section from the configuration. If the section in fact existed, return True. Otherwise return False.