参考链接:https://blog.csdn.net/haiyi_guo/article/details/97792968 多谢博主啦!
按照顺序 , 今天先来实现读取配置文件。用到的是Python中的configparser 类, 官方文档 https://docs.python.org/3/library/configparser.html ,中文文档 https://cloud.tencent.com/developer/section/1367819 。
自己练习写的小例子:
import configparser
config = configparser.RawConfigParser({"opt1":"test1","opt2":"test2"}) #DEFAULT 部分
config.add_section('Section1') #添加Section
config.set('Section1', 'an_int', '15')
config.set('Section1', 'a_bool', 'true')
config.set('Section1', 'a_float', '3.1415')
config.set('Section1', 'baz', 'fun')
with open("test.ini","w") as configfile:
config.write(configfile)
config.read("test.ini")
a_float = config.getfloat("Section1","a_float")
print(a_float)
print(config.get('Section1', 'foo'))
print(type(config.sections()))
1. 先获取配置文件的目录
(
# 打印当前文件上一层目录E:/PycharmProjects/autodemo1/config
print(os.path.dirname(__file__))
#打印当前文件的绝对路径E:\PycharmProjects\autodemo1\config\readConfig.py
print(os.path.abspath(__file__))
#E:\PycharmProjects\autodemo1\config
)
path = os.path.split(os.path.abspath(__file__))[0]
configFile = os.path.join(path,"config.ini")
2. 先简单写db信息, 尝试读取相应配置
[db]
db_host = localhost
db_port = 8080
(config.ini 内容)
class ReadConfig:
def __init__(self):
self.config = configparser.ConfigParser()
self.config.read(configFile)
def get_db_host(self):
host = self.config.get("db","db_host")
return host
def get_db_port(self):
port = self.config.get("db","db_port")