脚本专栏 发布日期:2025/11/6 浏览次数:1
前言:目前我们使用的绝大多数计算机程序,无论是办公软件,浏览器,甚至游戏、视频都是通过菜单界面系统配置的,它几乎成了我们使用机器的默认方式。而在python中,也有这样的一个配置模块可以把代码可配置化。
什么是配置文件
"color: #ff0000">读取配置文件
"htmlcode">
from configparser import ConfigParser
# 创建一个操作配置文件的对象(文件解析对象)
conf = ConfigParser()
# 读取配置文件
conf.read("conf.ini", encoding="utf8")
# 获取所有section
res2 = conf.sections()
print("这是res2:{}\n".format(res2))
# 获取对应section下的option
res3 = conf.options("logging")
print("这是res3:{}\n".format(res3))
# 获取对应section下的所有键值对
res4 = conf.items("logging")
print("这是res4:{}\n".format(res4))
# get方法:读取出来的内容,都是字符串
res5 = conf.get("logging", "level")
print("这是res5:{}".format(res5), type(res5))
# getint方法:读取出来的内容,都是int类型
res6 = conf.getint("mysql", "port")
print("\n这是res6:{}".format(res6), type(res6))
"color: #ff0000">写入配置文件
"htmlcode">
from configparser import ConfigParser
# 创建一个操作配置文件的对象(文件解析对象)
conf = ConfigParser()
conf.add_section('test')
conf.set('test', 'name', 'Amy')
conf.write(open('conf.ini', "a", encoding="utf-8"))
ConfigParser的封装
"htmlcode">
from configparser import ConfigParser
class MyConf:
def __init__(self, filename, encoding="utf8"):
self.filename = filename
self.encoding = encoding
self.conf = ConfigParser()
self.conf.read(filename, encoding)
def get_str(self, section, option):
return self.conf.get(section, option)
def get_int(self, section, option):
return self.conf.getint(section, option)
def get_float(self, section, option):
return self.conf.getfloat(section, option)
def get_bool(self, section, option):
def write_data(self, section, option, value):
self.conf.set(section, option, value)
self.conf.write(open(self.filename, "a", encoding=self.encoding))
if __name__ == '__main__':
print(conf.get_str("conf.ini", "test","name")) # 测试
总结