ConfigParser类的用法,配置文件的读写
配置文件格式
[INFO]
name=xiaoming
age=34
address=pudong
[LEARN]
code=python
number=45
其中,INFO,LEARN这些是section,name,age,address这些是option
读取配置文件
config=ConfigParser()
config.read('./config/default')
section=config.sections()
value=config.get("INFO","name")
value_num=config.getint("INFO","age")
section_flag=config.has_section("INF")
option_flag=config.has_option("INFO","test")
使用get方法读取的key都是string,需要自己再进行数据转化,可以使用getInt,getBoolean等方法直接转化
写入配置文件
首先需要创建一个配置文件
write_config=ConfigParser()
write_config["INFO"]={
"name":"xiaohong",
"age":13
}
write_config["ADDRESS"]={}
options=write_config["ADDRESS"]
options["city"]="pudong"
write_config.set("ADDRESS","stree","pudong")
with open("./config/write","w") as configfile:
write_config.write(configfile)
将代码封装成类
from configparser import ConfigParser
import configparser
class ConfigHandler():
def __init__(self,path):
self.path=path
self.config=ConfigParser()
def getKeys(self,section,option):
self.config.read(self.path)
if self.config.has_section(section):
if self.config.has_option(section,option):
return self.config.get(section,option)
else:
raise configparser.NoOptionError
else:
raise configparser.NoSectionError
def setOptions(self,section,option,value):
self.config[section]={}
self.config.set(section,option,value)
with open(self.path,"w") as writefile:
self.config.write(writefile)
config_handler=ConfigHandler('./config/default')
value=config_handler.getKeys("INFO","name")
print(value)
config_handler=ConfigHandler('./config/write')
config_handler.setOptions("INFO","name",'tiantian')
将读写config文件改成一个工具类
如果要封装成一个工具类,最好是写成一个类方法,直接调用
from configparser import ConfigParser
import os
import configparser
class ConfigHandler():
@classmethod
def get_keys(cls,path,section,option):
config=ConfigParser()
if not os.path.exists(path):
raise FileExistsError
config.read(path)
if config.has_section(section):
if config.has_option(section,option):
value=config.get(section,option)
return value
else:
raise configparser.NoOptionError
else:
raise configparser.NoSectionError
value=ConfigHandler.get_keys("./config/default","INFO",'name')
print(value)
|