【python基础】configparser之参数配置

大家都嘲讽,深度学习工程师就是调参狗。可见,调参在深度学习中的重要性。python中有用于统一配置管理参数的包configparser


创建配置文件

#-*-coding:utf-8-*-
import configparser

cf = configparser.ConfigParser()

cf.add_section('birthday')
cf.set('birthday','month',value='June')
cf.set('birthday','day',value='12')

cf.add_section('school')
cf.set('school','address',value='Jingzhai Road')
cf.set('school','name',value='USTC')

with open('information.txt','a') as configration:
    cf.write(configration)

几点注释:
1. 第四行:新建一个Configparser实例。此处可选的方法有:ConfigparserRawConfigParserSafeConfigParser,像我们这样的低端玩家直接使用Configparser就好;
2. 第六行:增加birthday组(section)
3. 第七行:增加month键,键值为June
4. 第十行:增加school
5. 第十四、十五:将实例写入到information.txt文件。打开文件模式可选为awa为在配置文件中添加内容,w为擦除原文件内容并写入。

写入完毕后的information.txt文件双击打开后如下图:
这里写图片描述


读取配置文件

依然以information.txt为例。如果文件夹中已经存在配置文件,我们要将详细的配置读取出来:

#-*-coding:utf-8-*-
import configparser

cf = configparser.ConfigParser()
cf.read('information.txt')

sections = cf.sections()
options = cf.options('birthday')
items = cf.items('birthday')
school_add = cf.get('school','address')
school_add2 = cf['school']['address']

print('Sections in config file:', sections)
print('Options in birthday section:', options)
print('items in birthday section:', items)
print('school address:', school_add)
print('school address2:', school_add2)

输出:

Sections in config file: ['birthday', 'school']
Options in birthday section: ['month', 'day']
items in birthday section: [('month', 'June'), ('day', '12')]
school address: Jingzhai Road
school address2: Jingzhai Road

几点注释:
1. 第五行:读取配置文件
2. 第七行:获取该配置文件的所有组(section)
3. 第八行:获取birthday组(section)的所有键的键名
4. 第九行:获取birthday组(section)的所有键名键值对
5. 第十行:获取school组(section),键名为address的键值。获取到的键值为字符串类型。
6. 第十一行:使用cf['school']['address']也可以达到和get同样的效果。


其他用法

  1. getint(section,option):获取键值,返回类型为整形;
  2. remove_section(section):删除名为section的组;
  3. remove_option(section,option):删除section组下面的option键;
  4. set(section,option,value):将section组下面的option键的键值设为value
  5. 如果想要更加简单地修改键值,可直接用记事本打开配置文件编辑。

进阶玩法,可参见博主miner_k的python的ConfigParser模块

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值