import configparser
conf = configparser.ConfigParser()
conf.read('MyConfig.txt', encoding='utf-8') # encoding解决中文乱码
mysql = config['mysql']
db = mysql.get('db')
# 判断是否有配置项
if not self.conf.has_section('MyConfig'):
conf.add_section('MyConfig')
# 判断配置项下是否有某选项
conf.has_option('MyConfig', '原始文件路径')
# 读取配置项的选项
conf.get('MyConfig', '原始文件路径')
# 设置选项
conf.set('MyConfig', '原始文件路径', filepath)
# 写入配置,要打开并写入txt或ini文件中
# 以擦除写入w的方式写入,以保留唯一的配置
# 打开txt时必须要指定编码方式,否则默认ANSII方式,再次读取时以utf-8读取报错
with open('MyConfig.txt', 'w', encoding='utf-8') as f:
conf.write(f)
config.sections() # 获取section节点
config.options('mysql') # 获取指定section 的options即该节点的所有键列表
config.get("mysql", "name") # 获取指定section下的options
config.getint("mysql", "proxy") # 将获取到值转换为int型
config.getboolean("mysql", "pool") # 将获取到值转换为bool型
config.getfloat("mysql", "time") # 将获取到值转换为浮点型
config.items("mysql") # 获取section的所用配置信息
config.set("mysql", "name", "root") # 修改db_port的值为69
config.has_section("mysql") # 是否存在该section
config.has_option("mysql", "password") # 是否存在该option
config.add_section("redis") # 添加section节点
config.set("redis", "name", "redis_admin") # 设置指定section 的options
config.remove_section("redis") # 整个section下的所有内容都将删除
config.remove_option("mysql", 'time') # 删除section下的指定options
config.write(open("Config", "w")) # 保存config
注意:在报错配置时要指定以utf-8的方式打开txt文件
问题一:当配置文件是ini文件,键值对不能加引号,逗号等,不能有注释。
从config.py中复制的键值对,由于加了引号,导致读取不到键值
问题二:ini配置用记事本修改,有可能添加了不可见的 BOM(Byte Order Mark)标记
这可能导致configparser
无法正确解析文件的第一行作为section header。可以使用支持去除BOM的文本编辑器(例如Notepad++)打开config.ini
如果不想使用文本编辑器,你也可以在代码中处理BOM。
def remove_bom(file_path):
# 读取文件内容
with open(file_path, 'r', encoding='utf-8-sig') as file:
content = file.read()
# 写回文件
with open(file_path, 'w', encoding='utf-8') as file:
file.write(content)
# 移除BOM
remove_bom('./app/config/config.ini')
config = configparser.ConfigParser()
config.read('./app/config/config.ini',encoding='utf-8')
station_clients = config['stations']
引用: