ConfigParser模块学习

ConfigParser模块在python中是用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。使用的配置文件的好处就是不用再程序中硬编码,可以是你的程序变得灵活起来。
注意:在python 3 中ConfigParser模块名已更名为configparser

读取配置文件

read(filename) 直接读取ini文件内容sections() 得到所有的section,并以列表的形式返回

options(section) 得到该section的所有option

items(section) 得到该section的所有键值对

get(section,option) 得到section中option的值,返回为string类型

getint(section,option) 得到section中option的值,返回为int类型

getfloat(section,option)得到section中option的值,返回为float类型

getboolean(section, option)得到section中option的值,返回为boolean类型

写入配置文件

add_section(section) 添加一个新的section

has_section(section) 判断是否有section

set( section, option, value) 对section中的option进行设置

remove_setion(section)删除一个section

remove_option(section, option)删除section中的option

write(fileobject)将内容写入配置文件。

import configparser
config = configparser.ConfigParser() config['DEFAULT'] = {'ServerALiveInterval': '',
'Compression': 'yes',
'CompressionLevel': ''}
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = ''
topsecret['ForwardXll'] = 'no'
config['DEFAULT']['ForwardXll'] = 'yes' with open('example.ini','w') as configfile:
config.write(configfile)
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardxll = yes [bitbucket.org]
user = hg [topsecret.server.com]
host port = 50022
forwardxll = no

配置文件config.ini如下:

    [user]
username = tom
password = ***
email = test@host.com [book]
bookname = python
bookprice = 25

注意:也可以使用:替换=

程序:

    # -* - coding: UTF-8 -* -
import ConfigParser
import sys reload(sys)
sys.setdefaultencoding("utf-8") #生成config对象
conf = ConfigParser.ConfigParser()
#用config对象读取配置文件
conf.read("config.ini")
#以列表形式返回所有的section
sections = conf.sections()
print 'sections:', sections #sections: ['user', 'book']
#得到指定section的所有option
options = conf.options("user")
print 'options:', options #options: ['username', 'password', 'email']
#得到指定section的所有键值对
useritem = conf.items("user")
print 'user:', useritem #user: [('username', 'tom'), ('password', '***'), ('email', 'test@host.com')]
#指定section,option读取值
str_val = conf.get("book", "bookname")
int_val = conf.getint("book", "bookprice") print "value for book's bookname:", str_val #value for book's bookname: python
print "value for book's bookprice:", int_val #value for book's bookprice: 25 #写配置文件
#更新指定section,option的值
conf.set("book", "bookname", "python learning")
#写入指定section增加新option和值
conf.set("book", "bookpress", u"人民邮电出版社")
#增加新的section
conf.add_section('purchasecar')
conf.set('purchasecar', 'count', '1')
#写回配置文件
conf.write(open("config.ini", "w"))

python常用模块(3)的更多相关文章

  1. Python常用模块之sys

    Python常用模块之sys sys模块提供了一系列有关Python运行环境的变量和函数. 常见用法 sys.argv 可以用sys.argv获取当前正在执行的命令行参数的参数列表(list). 变量 ...

  2. Python常用模块中常用内置函数的具体介绍

    Python作为计算机语言中常用的语言,它具有十分强大的功能,但是你知道Python常用模块I的内置模块中常用内置函数都包括哪些具体的函数吗?以下的文章就是对Python常用模块I的内置模块的常用内置 ...

  3. python——常用模块2

    python--常用模块2 1 logging模块 1.1 函数式简单配置 import logging logging.debug("debug message") loggin ...

  4. python——常用模块

    python--常用模块 1 什么是模块: 模块就是py文件 2 import time #导入时间模块 在Python中,通常有这三种方式来表示时间:时间戳.元组(struct_time).格式化的 ...

  5. Python常用模块——目录

    Python常用模块学习 Python模块和包 Python常用模块time & datetime &random 模块 Python常用模块os & sys & sh ...

  6. python 常用模块之random,os,sys 模块

    python 常用模块random,os,sys 模块 python全栈开发OS模块,Random模块,sys模块 OS模块 os模块是与操作系统交互的一个接口,常见的函数以及用法见一下代码: #OS ...

  7. python常用模块之时间模块

    python常用模块之时间模块 python全栈开发时间模块 上次的博客link:http://futuretechx.com/python-collections/ 接着上次的继续学习: 时间模块 ...

  8. python常用模块之subprocess

    python常用模块之subprocess python2有个模块commands,执行命令的模块,在python3中已经废弃,使用subprocess模块来替代commands. 介绍一下:comm ...

  9. python常用模块之string

    python常用模块string模块,该模块可以帮我们获取字母.数字.特殊符号. import string #打印所有的小写字母 print(string.ascii_lowercase) #打印所 ...

  10. python常用模块-调用系统命令模块(subprocess)

    python常用模块-调用系统命令模块(subprocess) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. subproces基本上就是为了取代os.system和os.spaw ...

随机推荐

  1. Sprint会议2

    昨天:准备查找安卓APP开发的有关资料,安装有关软件 今天:自己制作一个安卓小程序,熟悉一下操作 遇到问题:安装遇到问题,环境配置出现问题

  2. datetime类型转换

    Select CONVERT(varchar(100), GETDATE(), 8):14:53:14 Select CONVERT(varchar(100), GETDATE(), 9): 06  ...

  3. Java锁的种类以及辨析

    锁作为并发共享数据,保证一致性的工具,在JAVA平台有多种实现(如 synchronized 和 ReentrantLock等等 ) .这些已经写好提供的锁为我们开发提供了便利,但是锁的具体性质以及类 ...

  4. Java 多线程之:偏向锁,轻量级锁,重量级锁

    一:java多线程互斥,和java多线程引入偏向锁和轻量级锁的原因? --->synchronized的重量级别的锁,就是在线程运行到该代码块的时候,让程序的运行级别从用户态切换到内核态,把所有 ...

  5. 分离链表法散列ADT

    分离链表法解决冲突的散列表ADT实现 数据结构定义如下: struct ListNode; typedef struct ListNode *Position; struct HashTbl; typ ...

  6. 前端切图相关ps技术

    标签(空格分隔): 前端切图 复制图层到一个新的ps文件 对于单个图层 1.选中图层 2.CTRL+A全选 3.CTRL+C 4.CTRL+N新建文件,文件大小默认就可以(背景透明也在这个面板设置), ...

  7. git add -A 和 git add . 的区别

    git add -A和 git add .   git add -u在功能上看似很相近,但还是存在一点差别 git add . :他会监控工作区的状态树,使用它会把工作时的所有变化提交到暂存区,包括文 ...

  8. mysqldumpslow 分析slow query日志和explain分析mysql查询结构

    mysqldumpslow的使用:比如我们要查询按时间返回前5条日志信息,格式如下:mysqldumpslow -s t -t 5 /var/log/mysql/slowquery_20180303. ...

  9. Json的JsonValueProcessor方法

    将对象转换成字符串,是非常常用的功能,尤其在WEB应用中,使用 JSON lib 能够便捷地完成这项工作. JSON lib能够将Java对象转成json格式的字符串,也可以将Java对象转换成xml ...

  10. DTCping 的简单使用与排错

    1. 工具下载路径 https://support.microsoft.com/zh-cn/help/918331/how-to-troubleshoot-connectivity-issues-in ...