Pyhton 标准库中的configparser,是用来解析配置文件的模块,本文针对该模块的读写进行案例介绍;
1、首先是定义配置文件读函数:
import configparser # 加载配置文件
# config read
def configFile_Read(section, option):
config_read = configparser.ConfigParser()
config_read.read(_file_sysConfig, encoding='utf-8')
if config_read.has_section(section):
if config_read.has_option(section, option):
value = config_read.get(section, option)
else:
value = ''
else:
value = ''
return value
函数中“_file_sysConfig”为定义的config文件;
2、之后就是定义配置文件写函数:
def configFile_Write(section, option, value):
config_write = configparser.ConfigParser()
config_write.read(_file_sysConfig, encoding='utf-8')
configFile_updateFlag = False
if config_write.has_section(section):
if config_write.has_option(section, option):
if (config_write.get(section, option) != str(value)):
config_write.set(section, option, str(value))
configFile_updateFlag = True
else:
config_write.set(section, option, str(value))
configFile_updateFlag = True
else:
config_write.add_section(section)
config_write.set(section, option, str(value))
configFile_updateFlag = True
if (True == configFile_updateFlag):
with open(_file_sysConfig, 'w', newline='', encoding='utf-8') as fileWriter:
config_write.write(fileWriter)
配置文件写函数不只是简单的写配置参数:
1)首先判断原来的配置文件是否有要写参数的“section”,然后再判断该“section”是否有要写参数的“option”,最后将对应的“section”、“option”的值读出来,与要写的值进行比对,若不一样,则请求参数更新,否则不需要写参数;
2)若原来的配置文件有要写参数的“section”,无要写参数的“option”,则直接请求写参数;
3)若原来的配置文件无要写参数的“section”,则直接请求写参数;
3、最后根据需求调用上述2个读写函数;
import os
import configparser
if __name__ == "__main__":
path_workspace = os.path.abspath(os.getcwd())
_file_sysConfig = path_workspace + "\\sysConfig.ini"
section_CANComm = 'CANComm'
option_ProtocolFile = 'File_Protocol'
# 写配置
path_ProtocolFile = configFile_Read(section_CANComm, option_ProtocolFile)
# 读配置
_file = './Protocol.xls'
configFile_Write(section_CANComm, option_ProtocolFile, _file)