Python-操作Config文件


阅读次数

Configparser

Configparser 是Python内置的一个config 文件读写的操作方法
操作具体如下,例如我们的config 文件如下:

[testSection]
testoption = testValue
testbool = true
testfloat = 3.14
testint = 77
testlist = 1,2,3,4,5,6
testoption2 = a,b,c

读取操作

import ConfigParser

conf = ConfigParser.ConfigParser()
conf.read("./test.conf")

# "获取 Boolean 类型"
conf.getboolean("testSection", "testBool")

# "获取 Float 类型"

conf.getfloat("testSection", "testFloat")

# "获取 Int 类型"
conf.getint("testSection", "testInt")

# "判断option是否存在"
conf.has_option("testSection", "testInt")

# "判断seciton是否存在"
conf.has_section("testSection")

# "获取seciotn 下的键值对,返回list"
conf.items("testSection")

# "获取所有的section,返回list"
conf.sections()

# "获取seciton 下所有的optin,返回list"
conf.options("testSection")

# "获取指定Value"
conf.get("testSection", "testOption")

写入操作

import ConfigParser

conf = ConfigParser.ConfigParser()

# 读取文件 1,2,3,4,5
conf.read("./test.conf")

# 添加section
if not conf.has_section("testSection"):
conf.add_section("testSection")

# 添加键值对 #
conf.set("testSection", "testOption", "testValue")

# 添加键值对List
list = ["a", "b", "c"]
str_list = ",".join(list)
conf.set("testSection", "testOption2", str_list )

# 写入文件
conf.write(open("./test.conf", "w"))

Demo

import ConfigParser

# 读取config 返回字典对象
def read_config(filepath):
section_dic = {}
option_dic ={}
conf = ConfigParser.ConfigParser()
conf.read(filepath)
allsection = conf.sections()
for i in allsection:
alloption = conf.options(i)
for j in alloption:
value = conf.get(i, j)
if "," in value:
value = value.split(",")
option_dic[j] = value
else:
option_dic[j] = value
section_dic[i] = option_dic
return section_dic

# 写入config文件
def write_config(filepath, section, option, value):
conf = ConfigParser.ConfigParser()
conf.read(filepath)
if not conf.has_section(section):
conf.add_section(section)
if type(value) is list:
strvalue = ",".join(value)
conf.set(section, option, strvalue)
else:
conf.set(section, option, value)
conf.write(open(filepath, "w"))

ConfigObj

第三方的一个Config文件读取操作,对Configparser,也比较方便

读取config文件

from  configobj import ConfigObj

# 读取配置文件
config =ConfigObj("./test.conf")

#获取section,下所有的键值对
section1 = config["testSection"]
print section1

#根据section 获取对应的值
value1 = section1["testoption"]
print value1


value2 = config["testSection"]["testoption"]

写入Config 文件

from configobj import ConfigObj

# 写入配置文件

config = ConfigObj("./test.conf")

# 可以没有Section ,直接写option
config["newoption"] = "newvalue"

# 创建section ,然后再写入option
config["section1"] = {}
config["section1"]["option1"] = "value1"
config["section1"]["option2"] = "value2"

# 可以创建字典,然后写入config
section2 ={
"option1":"value1",
"option2":"value2"
}
config["section2"] = section2

# 可以直接给value 传入list
config["section3"] = {}
config["section3"]["option1"] = ["a","b","c"]

config.write()

Ps: 参考官方文档 ConfigObl doc_

">