python中利用ConfigParser模块读取配置文件

配置文件

配置文件一般用于保存一些代码运行所需要的参数信息,如.cfg文件,一个具体配置文件内容如下:

[Common]
image_size: 448
batch_size: 16
num_classes: 20
max_objects_per_image: 20
[DataSet]
name: yolo.dataset.text_dataset.TextDataSet
path: data/pascal_voc.txt
thread_num: 5
[Net]
name: yolo.net.yolo_tiny_net.YoloTinyNet
weight_decay: 0.0005
cell_size: 7
boxes_per_cell: 2
object_scale: 1
noobject_scale: 0.5
class_scale: 1
coord_scale: 5
[Solver]
name: yolo.solver.yolo_solver.YoloSolver
learning_rate: 0.00001
moment: 0.9
max_iterators: 1000000
pretrain_model_path: models/pretrain/yolo_tiny.ckpt
train_dir: models/train

这是一份训练深度学习模型以实现目标检测的配置文件train.cfg,里面保存了学习率、batch_size等信息。其中[Common], [DataSet], [Net], [Solver]叫Section,Section中的内容叫option, 如Common中的Option有:image_size, batch_size, num_classes, max_objects_per_image。每一个option都会有取值。

ConfigParser模块读取配置文件

  • read(config_filename):读取配置文件内容
  • sections():列表形式返回配置文件所有section
  • options(sec):返回sec中的所有option
  • items(sec):返回sec中所有option及其取值
  • get(sec, opt):返回sec中opt的值
  • getint(sec, opt):同get(),但返回值是int型
  • getfloat(sec, opt):类似getint()

实例

"""python
Description: a test code of reading configure file with ConfigParser library.
Author: Meringue
Date: 2018/2/7 
"""

import ConfigParser

# create a configure object and read a configure file
conf_file = "train.cfg" 
config = ConfigParser.ConfigParser()
config.read(conf_file)

secs = config.sections()  # return a list of all section names.
print "secs = ", secs #['Common', 'DataSet', 'Net', 'Solver']

common = config.options(secs[0])
print "options in commom = ", common

common_items = config.items(secs[0])
print "items in commom = ", common_items

image_size = config.get(secs[0], "image_size")
print "image_size = ", image_size

batch_size = config.getint(secs[0], "batch_size")
print "batch_size = ", batch_size

learning_rate = config.getfloat("Solver", "learning_rate")
print "learning_rate = ", learning_rate

代码运行结果

secs =  ['Common', 'DataSet', 'Net', 'Solver']
options in commom =  ['image_size', 'batch_size', 'num_classes', 'max_objects_per_image']
items in commom =  [('image_size', '448'), ('batch_size', '16'), ('num_classes', '20'), ('max_objects_per_image', '20')]
image_size =  448
batch_size =  16
learning_rate =  1e-05

猜你喜欢

转载自blog.csdn.net/sinat_34474705/article/details/79283634