python开发config层_Python内置模块ConfigParser实现配置读写功能的方法

Python内置模块ConfigParser实现配置读写功能的方法

发布时间:2020-10-02 10:36:57

来源:脚本之家

阅读:86

作者:苍松

本文实例讲述了Python内置模块ConfigParser实现配置读写功能的方法。分享给大家供大家参考,具体如下:

用于对特定的配置进行操作,当前模块的名称在 python 3.x 版本中变更为 configparser。

#配置文件test.cfg

[section1]

k1 = v1

k2 :v2

k3 = 1

[section2]

k1 = v1

#coding:utf-8

import ConfigParser

config = ConfigParser.ConfigParser()

config.read('test.cfg')

# ########## 读 ##########

#获取所有sections.

secs = config.sections()

print secs #['section1', 'section2']

#获取制定section的键key

options = config.options('section1')

print options #['k1', 'k2', 'k3']

#获取指定section的键值对key-value

item_list = config.items('section1')

print item_list #[('k1', 'v1'), ('k2', 'v2'), ('k3', '1')]

#获取指定key的value

# 获取字符串类型的value

val1 = config.get('section1','k1')

# 获取整型的value

val2 = config.getint('section1','k3')

# ########## 增改删 ##########

# 增加section

if not config.has_section('section3'):

config.add_section('section3')

config.write(open('test.cfg', "w"))

#设置option

if not config.has_section('section3'):

config.set('section3','k1',11111)

config.write(open('test.cfg', "w"))

# 移除option

ret = config.remove_option('section3','k1')

print ret #True or False

config.write(open('test.cfg', "w"))

# 移除section

ret = config.remove_section('section3')

print ret #True or False

config.write(open('test.cfg', "w"))

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值