python 写配置项如个没有section就新建一个section再写
可以使用configparser模块来操作配置文件。下面是一个示例代码,用于写入配置项到配置文件中。如果配置文件中不存在指定的section,则会自动创建该section。
import configparser
def write_config(config_file, section, option, value):
# 创建 ConfigParser 对象
config = configparser.ConfigParser()
# 读取配置文件
config.read(config_file)
# 检查指定的 section 是否存在,如果不存在则创建
if not config.has_section(section):
config.add_section(section)
# 设置或更新配置项的值
config.set(section, option, value)
# 写入配置文件
with open(config_file, 'w') as file:
config.write(file)
# 示例用法
write_config('config.ini', 'SectionOne', 'OptionOne', 'ValueOne')
执行上述代码后,会将OptionOne=ValueOne写入到config.ini配置文件的[SectionOne]部分。如果config.ini文件不存在,则会自动创建该文件,并写入配置项。
注意:在写入配置项之前,需要先安装configparser模块。可以使用以下命令安装:
pip install configparser
``
原文地址: https://www.cveoy.top/t/topic/idz0 著作权归作者所有。请勿转载和采集!