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

yipeiwu_com5年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

python动态性强类型用法实例

本文实例分析了python动态性强类型用法。分享给大家供大家参考。具体如下: Python变量声明和定义 与C#不同,Python在使用变量之前无须定义它的类型,试着运行下面的例子:...

用Python写一个无界面的2048小游戏

用Python写一个无界面的2048小游戏

以前游戏2048火的时候,正好用其他的语言编写了一个,现在学习python,正好想起来,便决定用python写一个2048,由于没学过python里面的界面编程,所以写了一个极其简单的无...

Python实现命令行通讯录实例教程

Python实现命令行通讯录实例教程

1、实现目标 编写一个命令行通讯录程序,可以添加、查询、删除通讯录好友及电话 2、实现方法 创建一个类来表示一个人的信息。使用字典存储每个人的对象,名字作为键。 使用pickle模块...

使用Python导出Excel图表以及导出为图片的方法

使用Python导出Excel图表以及导出为图片的方法

本篇讲下如何使用纯python代码将excel 中的图表导出为图片。这里需要使用的模块有win32com、pythoncom模块。 网上经查询有人已经写好的模块pyxlchart,具体代...

python实现倒计时小工具

本文实例为大家分享了python实现倒计时小工具的具体代码,供大家参考,具体内容如下 #!/usr/bin/env python # coding=utf-8 import th...