1、安装configparser模块
python使用自带的configparser模块来读取配置文件,配置文件的形式类似windows中的ini文件。在使用前需要安装,使用pip安装即可,
2、新建一个config.ini文件
[Mysql-Database]
host=localhost
user=root
password=123456
db=test
charset=uft8
[Email]
host = https://mail.qq.com
address = 23627329@qq.com
password = 123456
3、新建一个readconfig.py文件,读取配置文件的信息
import configparser
cf = configparser.ConfigParser()
#config文件跟readconfig在同一级目录下
cf.read("config.ini")
#读取文件中的所有section,每个section由[]包裹,并以列表的形式返回
secs = cf.sections()
print(secs)
#获取某个section名为Mysql-Database所对应的全部键
options = cf.options("Mysql-Database")
print(options)
#获取某个section名为Mysql-Database所对应的全部键值对
items = cf.items("Mysql-Database")
print(items)
#获取[Mysql-Database]中host对应的值
host = cf.get("Mysql-Database", "host")
print(host)
运行结果如下:
['Mysql-Database', 'Email']
['host', 'user', 'password', 'db', 'charset']
[('host', 'localhost'), ('user', 'root'), ('password', '123456'), ('db', 'test'), ('charset', 'uft8')]
localhost
4、将读取配置文件readconfig.py封装到一个类中
import configparser
import os
class ReadConfig:
def __init__(self,filepath=None):
if filepath:
self.configpath = filepath
else:
root_dir = os.path.dirname(os.path.abspath('.'))
self.configpath = os.path.join(root_dir, 'config.ini')
self.cf = configparser.ConfigParser()
self.cf.read(self.configpath)
def get_db(self, param):
# 读取“Mysql-Database”section底下param对应的值
value = self.cf.get("Mysql-Database", param)
return value
def set_db(self, param, text):
# 编辑“Mysql-Database”section底下param对应的值为text
self.cf.set("Mysql-Database", param, text)
# 将改动写入到配置文件中
with open(self.configpath, "w+") as f:
return self.cf.write(f)
def add_db(self, title):
# 新增一个叫title的section
self.cf.add_section(title)
# 将改动写入到配置文件中
with open(self.configpath, "w+") as f:
return self.cf.write(f)
if __name__ == '__main__':
test = ReadConfig()
test.set_db("host", "changed_host")
t = test.get_db("host")
test.add_db("add")
print(t)