配置文件的简单操作
先贴代码
from configparser import ConfigParser class homework(): def __init__(self,file_path,encoding = "UTF-8"): self.cf = ConfigParser() self.cf.read(file_path,encoding) def get_IntValue(self,section,option): return self.cf.getint(section,option) def get_StrValue(self,section,option): return self.cf.get(section,option) def get_BoolValue(self,section,option): return self.cf.getboolean(section,option) def get_FolatValue(self,section,option): return self.cf.getfloat(section,option) def get_section(self): return self.cf.sections() def get_item(self,section): return self.cf.items(section) if __name__ == "__main__": hw = homework("Section.cfg") print(hw.get_section()) for i in hw.get_section(): print("{}的参数为{}".format(i,hw.get_item(i)))
#Section.cfg [hunman] name = "王小明" sex = "男" age = 30 work = "Rider" [language] programming = "Python" Communication = "Chinese" Examination = "English" [Dict] value_1 = 1 value_2 = 2 Value_3 = 3
注意点:
1.配置文件可以以cfg或者conf结尾,效果无区别
2.配置文件一定是以[]标明区域
3.区域内的section和option可以理解成键值对形式
4.针对不同option类型可以使用不同的默认方法,来更准确的输出内容