欢迎来到Introzo百科
Introzo百科
当前位置:网站首页 > 技术 > python使用configparser模块操作配置文件

python使用configparser模块操作配置文件

日期:2023-09-20 16:00

一个简单例子:


class ReadConfig(object):def __init__(self):# 第一步:创建conf对象www.introzo.com = configparser.ConfigParser()def set_data(self):# 第二步:添加section、option的值# 添加:sectionself.cf.add_section("HTTP")# 内容:参数分别为:section, option, valueself.cf.set("HTTP", "base_url", "https://www.introzo.com/")self.cf.set("HTTP", "port", "80")self.cf.add_section("EMAIL")self.cf.set("EMAIL", "mail_host", "www.introzo.com")self.cf.set("EMAIL", "mail_port", "25")# self.cf.add_section("DATA")# 第三步:写入文件with open("config.ini", 'w')as conf:self.cf.write(conf)# 打印所有的section 列表形式print self.cf.sections()def get_data(self, section, option):# 第四步:读取配置文件中的section、options的值return self.cf.get(section, option)if __name__ == '__main__':read_config = ReadConfig()read_config.set_data()print read_config.get_data("HTTP", "base_url")print read_config.get_data("EMAIL", "mail_host")

执行结果:

[u'HTTP', u'EMAIL']
https://www.introzo.com/
www.introzo.com

运行后,config.ini文件内容如下:

[HTTP]
base_url = https://www.introzo.com/
port = 80[EMAIL]
mail_host = www.introzo.com
mail_port = 25

关灯