操作ini文件
1.ini介绍
python项目可以使用ini文件或者config文件做配置文件,并提供了configparser.ConfigParser来读取ini, ini配置文件以.ini结尾,config文件以.config结尾,他们的配置方式相同,本文以ini文件量讲解读取方法。下面是一份ini配置实例文件
2.ini的应用场景
主要用于项目的相关配置,比如说数据库信息,环境信息,路径信息等
[host]是节点
[host]
api_sit_url=https://api.binstd.com
api_uat_url=https://api.binstd1.com
[mysql]
host=127.0.0.1
port=3306
user=root
password=yourpassword
dbname=test
[redis]
host=127.0.0.1
port=6379
password=88888
db=0
3.读写ini文件
配置文件由两部分组成sections与items,sections 用来区分不同的配置块,items 是sections下面的键值。
python3中提供了标准模块configparser,该模块下有一个ConfigParser类,可以用来解析ini文件
读取ini相关操作
- read(filename) 读取文件内容(当配置文件有中文时,在调用read()方法时,需要传encoding="utf-8-sig"参数
- sections() 获取所有的section,以列表形式返回
- options(section) 获取指定section的所有options,以列表形式返回
- items(section) 获取指定section的所有键值对,以列表形式返回
- get(section, option) 获取指定option的值,返回类型string
写入ini相关操作
- write(fp) 将config对象写入ini文件
- add_section(section) 添加一个新的section
- set(section, option, value) 对指定section下的某个option赋值
- remove_section(section) 删除某个section
- remove_option(section, option) 删除某个section下的某个option
判断ini的节点
- has_section(section)判断section是否存在,返回值为bool
- has_option(section,option)判断指定的section或者option是否存在,返回值为bool
import configparser
import logging
from conftest import PROJECT_PATH
class ReadIniData():
def __init__(self,file_path):
self.file_path = file_path
self.con = configparser.ConfigParser()
try:
self.con.read(file_path,'utf8')
except Exception as e:
msg = "读取ini文件失败"+e
logging.error(msg)
def get_all_sections(self):
"""
获取ini文件所有的块section,返回为list
:return:
"""
try:
return self.con.sections()
except Exception as err:
msg = "未找到节点"+err
logging.error(msg)
def get_all_options(self,section):
"""
获取ini文件指定块的项
:param section:需要指定的项
:return:返回指定块的项(列表形式)
"""
try:
return self.con.options(section)
except Exception as err:
msg = "未找指定节点的options" + err
logging.error(msg)
def get_all_items(self,section):
"""
获取指定section的所有键值对
:param section: 返回指定块的项(列表形式)
:return: section的所有键值对(元祖形式)
"""
try:
return self.con.items(section)
except Exception as err:
msg = "未找指定节点的items" + str(err)
logging.error(msg)
def get_target_option(self,section,option):
"""
获取指定section和option的值
:param section:
:param option:
:return:目标值
"""
try:
return self.con.get(section,option)
except Exception as err:
msg = "未找指定节点的item:" + str(err)
logging.error(msg)
def write_ini(self):
"""
修改后写入文件
:return:
"""
with open(self.file_path,mode='w') as file:
self.con.write(file)
def add_section(self,sec):
"""
添加节点
:param sec:
:return:
"""
try:
self.con.add_section(sec)
self.write_ini()
except Exception as err:
msg = "添加section失败" + str(err)
logging.error(msg)
def remove_section(self,sec):
"""
删除节点
:param sec:
:return:
"""
try:
self.con.remove_section(sec)
self.write_ini()
except Exception as err:
msg = "添加section失败" + str(err)
logging.error(msg)
def set_option(self,sec,opt,new_value):
"""
修改指定section和option的值
:param sec:
:param opt:
:param new_value:
:return:
"""
try:
self.con.set(sec,opt,new_value)
self.write_ini()
except Exception as err:
msg = "修改option的值失败" + str(err)
logging.error(msg)
def remove_option(self,sec,option):
"""
删除某个section下的某个option
:param sec:
:param option:
:return:
"""
try:
self.con.remove_option(sec,option)
self.write_ini()
except Exception as err:
msg = "删除option失败" + str(err)
logging.error(msg)
file_path = PROJECT_PATH+"/config/setting.ini"
read_ini = ReadIniData(file_path)
# sections = read_ini.get_all_sections()
# print("Sctions:")
# print(sections)
# options = read_ini.get_all_options("redis")
# print("Options:")
# print(options)
# items = read_ini.get_all_items("redis")
# print("Items:")
# print(items)
# item = read_ini.get_target_option("redis","password")
# print("target Items:")
# print(item)
# read_ini.add_section("testdata")
# print("add section:")
# print(read_ini.get_all_sections())
# read_ini.remove_section("testdata")
# print("remove section:")
# print(read_ini.get_all_sections())
#异常测试,没有section时的error
# read_ini.set_option("student","age","19")
# read_ini.set_option("redis","port","10086")
# print(read_ini.get_target_option("redis","port"))
read_ini.set_option("redis","port","10086")
read_ini.remove_option("redis","port")
print("remove option:") #先添加,后移除,所有结果为None
print(read_ini.get_target_option("redis","port"))
read_ini.set_option("redis","port","10086")
print("set option:")
print(read_ini.get_target_option("redis","port"))
应该还缺个根据section和option来添加值的,仔细想想觉得和set_option大同小异