在项目制的工作中往往会用到配置文件,这样可以灵活配置和切换,ini最常见一种配置文件类型,其使用python自带的configparser模块实现配置文件的写入、更新、删除、读取等操作。
[Mock]
mock_ip = 127.0.0.1
mock_port = 9991
[Log]
log_name = mock.log
log_level = info
cache_name = cache.txt
[Interface]
interface_ip = 127.0.0.1
interface_port = 19991
ini结构:
片段(section)对应 [Mock]
选项(option)对应 mock_ip,相当于key
值(value)对应127.0.0.1,相当于value
pip install configparser
import configparser
import os
# 读取配置文件
def read_config():
root_dir = os.path.dirname(os.path.dirname(__file__)) # # 获取当前文件所在目录
config_dir = os.path.join(root_dir, 'config', 'config.ini') # 组装config.ini路径,也可以直接写配置文件的具体路径,不用自动获取
cf = configparser.ConfigParser()
cf.read(config_dir, encoding="utf-8") # 读取config.ini
return cf
if __name__ == '__main__':
cf = read_config()
mock_ip = cf.get('Mock', 'mock_ip')
mock_port = cf.getint('Mock', 'mock_port') # 注意端口要用getint方法获取
print(mock_ip)
print(mock_port)
# 读取配置文件 常用的方法介绍
cf.read(filename) # 读取文件,返回filename的list
cf.sections() # 获取配置文件中所有sections的list
cf.options(section) # 获取指定section的键值list
cf.items(section) # 获取指定section下所有的键值对list
cf.get(section, key) # 获取指定section下指定key的value值, 返回str
cf.getint(section, key) # 获取指定sections下指定key的value值, 返回int
cf.getfloat(section, key) # 获取指定sections下指定key的value值, 返回float
cf.getboolean(section, key) # 获取指定sections下指定key的value值, 返回boolean
cf.has_section(section) # 获取是否包含某个section,返回boolean
cf.has_option(section,key) # 获取是否包含某个section的某个键,返回boolean
# 写入配置文件 常用方法介绍
cf = configparser.ConfigParser() # 实例化对象
cf.read(self.filename) # 读取文件,如果是重新写入,覆盖原有内容不需要读取
cf.add_section(section) # 添加sections值
cf.set(section, option, value) # 在指定的sections中添加键值对
cf.remove_section(section) # 移除sections, 需要先cf.read(filename)
cf.remove_option(section, option) # 移除指定sections下的options, 需要先cf.read(filename)
# 样例介绍
class WriteConfig():
"""写入config文件"""
def __init__(self, filename, filepath=r"D:\python_file\boke\config"):
self.filename = filename
os.chdir(filepath)
self.cf = configparser.ConfigParser()
self.cf.read(self.filename) # 如果修改,则必须读原文件
def _with_file(self):
# write to file
with open(self.filename, "w+") as f:
self.cf.write(f)
def add_section(self, section):
# 写入section值
self.cf.add_section(section)
self._with_file()
def set_options(self,section, option, value=None):
"""写入option值"""
self.cf.set(section, option, value)
self._with_file()
def remove_section(self, section):
"""移除section值"""
self.cf.remove_section(section)
self._with_file()
def remove_option(self, section, option):
"""移除option值"""
self.cf.remove_option(section, option)
self._with_file()