ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

Python-封装配置文件

Python-封装配置文件

在这里插入图片描述

在这里插入图片描述

Code

[url]
baidu = http://www.baidu.com[value]
send_value = 百度[server]
ip = 220.181.111.188

封装的格式可以套用

# 封装,类似函数调用
import configparserclass ReadConfigIni():def __init__(self,filename):self.cf = configparser.ConfigParser()self.cf.read(filename)def getConfigValue(self,section,name):value = self.cf.get(section,name)# print(value)return valueDoConfigIni = ReadConfigIni("test.ini")  #路径+文件名
BaiUrl = DoConfigIni.getConfigValue("url","baidu")
print("通过函数getConfigValue获得的值:",BaiUrl)

cf.ini文件

[db]
db_host = 127.0.0.1
db_port = 80
db_user = root
db_pass = root
host_port = 69[concurrent]
thread = 10
processor = 20
kong = 

op_cf.py文件

ini文件的增删查找演示

操作完成后都要加上 config.write(open(“cf.ini”,“w”)) (易错点)

# author:xiaowang
# date:2023/12/6
# 需求:ini文件的增删查找演示 操作完成后都要加上 config.write(open("cf.ini","w"))  #写入ini配置文件(易错点)
# 操作文档py
import configparserconfig = configparser.ConfigParser()   #实例化配置文件
config.read("cf.ini",encoding="utf-8")  #读取配置文件# 查找/读取操作
print(config.sections()) #读取所有的节
print(config.options("db"))  #指定节中键
print(config.get("db", "db_host")) #指定db节中db_host键中的值
print(config.get("concurrent","processor")) #指定节中的指定键的值
print(config.get("concurrent","kong"))
print(config.items("db"))  #输出指定db节的所有键值对(k:v)# 修改操作并通过读取验证
config.set("db","db_port","80") #将原来db_port的值69修改为80
config.write(open("cf.ini","w"))
print(config.get("db","db_port"))# 检查section 或 参数是否存在 (返回True或False)【适用在条件判断中if语句】
print(config.has_option("concurrent","thread")) #查找concurrent存在的thread节
print(config.has_option("concurrent","aa"))  #查找concurrent不存在的aa元素
print(config.has_option("concurrent","kong"))  #查找存在的kong节,只有k ,没有v(kong= )
print(config.has_section("db"))  #查找存在的db节
print(config.has_section("1b"))  #查找不存在的1b节# 添加,先判断节是否存在,若不存在添加节default
if not config.has_section("default"):config.add_section("default")
if not config.has_option("default","db_host"):config.set("default","db_host","1.1.1.1")
config.write(open("cf.ini","w"))  #写入ini配置文件(易错点)print(config.items("default"))# 删除某个节并查看所有节
config.remove_section("default")
config.write(open("cf.ini","w"))
print(config.sections())
返回列表