一、编辑ini格式的配置文件
[strings]
# Mode : train, test, serve
mode = train
working_directory = model_dir
dataset_path=train_data/
test_path=test_data/
;这是备注
[ints]
steps_per_checkpoint = 2
num_dataset_classes=10
dataset_size=50000
im_dim=32
num_channels = 3
num_files=6
images_per_file=10000
epochs=2
[floats]
keeps=0.5
上面是一段ini格式的配置文件内容。配置文件可以在pycharm中直接新建扩展名为ini的文件生成。写的时候每一部分以[section](上面代码中的[strings])开始, option=value结尾;备注以;开头;section不可重名。
二、读取配置文件信息
import configparser
def get_config(config_file='config.ini'):
parser=configparser.ConfigParser()
parser.read(config_file)
# get the ints, floats and strings
_conf_ints = [(key, int(value)) for key, value in parser.items('ints')]
_conf_floats = [(key, float(value)) for key, value in parser.items('floats')]
_conf_strings = [(key, str(value)) for key, value in parser.items('strings')]
#print(parser.get('ints','steps_per_checkpoint'))
return dict(_conf_ints + _conf_floats + _conf_strings)
if __name__ == '__main__':
print(get_config())
如上所示,用configparser包读取配置文件信息。一种是用get方法:
get(section, option)
另外一种是用列表推导式,得到一个包含字典的列表。