欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python处理conf格式文件

程序员文章站 2022-05-28 15:34:59
...

通常配置文件的后缀是.conf,那我们应该怎么处理这类文件呢?现在我们用python语言来处理这类文件。
python2.x内置了ParserConfig模块用于处理文件,该模块在python3中有一点变化,基本上是一样的。

文件样例

#test.conf
[db]
db_host = 127.0.0.1
db_port = 3306
db_user = root
db_password = xyz123456
[handle]
processor = 20
thread = 10

基本术语

  1. section: e.g. db, handle
  2. option: e.g. db_host, db_port, thread等
  3. item: e.g. db_host = 127.0.0.1, db_port = 3306等

python处理

import ConfigParser
cf = ConfigParser.ConfigParser()
#读
cf.read("test.conf")
#获取所有的sections
sections = cf.sections()
print(sections)
#获取某个section下的所有options
options = cf.options("db")
print(options)
#获取某个section下的所有items
items = cf.items("db")
print(items)
host_value = cf.get("db", "db_host") #返回str类型
print(host_value)
port_value = cf.getint("db", "db_port") #返回int类型,类似有:getfloat(), getboolean()
print(port_value)
#修改
cf.set("db", "db_password", 123456)
#删除
cf.remove_option("handle", "thread")
cf.remove_section("handle")
#将改变写入文件
cf.write(open("test.conf", "a"))
#写
#添加一个section
cf.add_section("test")
#添加section下的item
cf.set("test", "count", 1)
#写入文件
cf.write(open("test.conf", "a"))

#print 结果
['db', 'handle']
['db_host', 'db_port', 'db_user', 'db_password']
[('db_host', '127.0.0.1'), ('db_port', '3306'), ('db_user', 'root'), ('db_password', 'xyz123456')]
127.0.0.1
3306
#打开文件,结果已经写入文件中了

END