python configparser使用

.ini文件由若干section(部分)组成, 而每一个section又由若干键值对组成。

以 example.ini为例:

[DEFAULT]
ServerAliveInterval  =  45
Compression  =  yes
CompressionLevel  =  9
ForwardX11  =  yes

[bitbucket.org]
User  =  hg

[topsecret.server.com]
Port  =  50022
ForwardX11  =  no

创建.ini文件

import configparser

# configd对象类似于字典
config = configparser.ConfigParser()
config["DEFAULT"] = {
    "ServerAliveInterval" : 45,
    "Comperssion": "yes",
    "ComperssionLevel": 9,
    "ForwardX11": "yes"
}

config["bitbucket.org"] = {}
config["bitbucket.org"]["user"] = "hg"

config["topsecret.server.com"] = {}
config["topsecret.server.com"]["Port"] = "50022"
config["topsecret.server.com"]["ForwardX11"] = "no"

with open("example.ini", "w") as fp:
    # 写入文件
    config.write(fp)

读取.ini文件

config = configparser.ConfigParser()
config.read("example.ini")

关于section

import configparser

config = configparser.ConfigParser()
config.read("example.ini")
# 获取section名称列表
print(config.sections()) # [‘bitbucket.org‘, ‘topsecret.server.com‘]
# 获取默认section名称
print(config.default_section) # DEFAULT
# 获取默认section对象
print(config.defaults())   # OrderedDict([(‘serveraliveinterval‘, ‘45‘), (‘comperssion‘, ‘yes‘), (‘comperssionlevel‘, ‘9‘), (‘forwardx11‘, ‘yes‘)])

# 判断是否包含对应的section
print(‘bitbucket.org‘ in config)
print(config.has_section("example.com"))

# 添加section的2种方式
config[‘example.com‘] = {}
config[‘example.com‘][‘username‘] = ‘python‘
config.add_section("example.com1")

config.write(open("tmp.ini", "w"))

# 删除section的2种方式
del config[‘example.com‘]
config.remove_section("example.com")
config.write(open("tmp.ini", "w"))

关于option

import configparser

config = configparser.ConfigParser()
config.read("example.ini")

# 这里的option于key对应
# 获取section对应的key列表
bitbucket_keys = config.options(‘bitbucket.org‘)
print(bitbucket_keys) # [‘user‘, ‘serveraliveinterval‘, ‘comperssion‘, ‘comperssionlevel‘, ‘forwardx11‘]

# 判断section中是否存在对应的key
print(config.has_option("bitbucket.org", "User"))
print(‘user1‘ in config.options(‘bitbucket.org‘))
print(‘user1‘ in config[‘bitbucket.org‘])

# 添加option
config[‘bitbucket.org‘][‘pwd‘] = ‘python‘
config.write(open("tmp.ini", "w"))

# 删除option的2种方式
del config[‘bitbucket.org‘][‘User‘]
config.remove_option("bitbucket.org", "User")
config.write(open("tmp.ini", "w"))

value相关

import configparser

config = configparser.ConfigParser()
config.read("example.ini")

# 获取key对应的value的2种方式
user = config[‘bitbucket.org‘][‘User‘]
user = config.get(‘bitbucket.org‘, ‘User‘)
print(user)  # hg

interval = config.getint("topsecret.server.com", "Port")
print(interval) # 45
compression = config.getboolean("topsecret.server.com", "ForwardX11")
print(compression)
# 还有 config.getfloat()

# 设置value的2种方式
config.set(‘bitbucket.org‘, ‘User‘, ‘peter‘)
config[‘bitbucket.org‘]["User"] = "peter"
config.write(open("tmp.ini", "w"))
时间: 2024-08-26 10:26:37

python configparser使用的相关文章

Python ConfigParser模块常用方法示例

 在程序中使用配置文件来灵活的配置一些参数是一件很常见的事情,配置文件的解析并不复杂,在Python里更是如此,在官方发布的库中就包含有做这件事情的库,那就是ConfigParser,这里简单的做一些介绍.      Python ConfigParser模块解析的配置文件的格式比较象ini的配置文件格式,就是文件中由多个section构成,每个section下又有多个配置项,比如:      [db]     db_host=192.168.1.1    db_port=3306    db_

python ConfigParser模块 配置文件解析

ConfigParser模块主要是用来解析配置文件的模块,像mysql,或者win下面的ini文件等等 下面我们来解析mysql的配置文件my.cnf my.cnf配置文件内容 [mysqld] datadir=/var/lib/mysql socket=/var/lib/mysql/mysql.sock user=mysql # Disabling symbolic-links is recommended to prevent assorted security risks symbolic

python ConfigParser例子02

#coding:utf-8 import ConfigParser class Conf(): def __init__(self,name): self.name = name self.cp = ConfigParser.ConfigParser() self.cp.read(name) def getSections(self): return self.cp.sections() def getOptions(self, section): if self.cp.has_section(

python ConfigParser例子01

import ConfigParser def writeConfig(filename): config = ConfigParser.ConfigParser() # set db section_name = 'db' config.add_section( section_name  ) config.set( section_name, 'dbname', 'MySQL') config.set( section_name, 'host', '127.0.0.1') config.se

Python ConfigParser

转载:http://wangwei007.blog.51cto.com/68019/1104911 在程序中使用配置文件来灵活的配置一些参数是一件很常见的事情,配置文件的解析并不复杂,在Python里更是如此,在官方发布的库中就包含有做这件事情的库,那就是ConfigParser,这里简单的做一些介绍. Python ConfigParser模块解析的配置文件的格式比较象ini的配置文件格式,就是文件中由多个section构成,每个section下又有多个配置项,比如: [db] db_host

Python ConfigParser 读取配置向 SafeConfigParser写配置项

#!/usr/bin/env python # -*-coding:utf-8 -*- __author__ = 'shylock' import sys,os import ConfigParser def is_dir(config_path): return os.path.isdir(config_path) def read4Conf(config_path="./config",config_file=None,allow_no_value=False): if(is_di

Python Configparser模块读取、写入配置文件

写代码中需要用到读取配置,最近在写python,记录一下. 如下,假设有这样的配置. [db] db_host=127.0.0.1 db_port=3306 db_user=root db_pass= [concurrent] thread=200 processor=400 可以使用ConfigParser模块来读取.写入配置. 1 #coding=utf-8 2 import ConfigParser 3 import sys 4 5 cf = ConfigParser.ConfigPars

Python ConfigParser的使用

1.基本的读取配置文件 -read(filename) 直接读取ini文件内容 -sections() 得到所有的section,并以列表的形式返回 -options(section) 得到该section的所有option -items(section) 得到该section的所有键值对 -get(section,option) 得到section中option的值,返回为string类型 -getint(section,option) 得到section中option的值,返回为int类型,

[Python]ConfigParser解析配置文件

最近发现很多接口配置都硬编码在souce file中了,于是就看了下python怎么解析配置文件,重构下这一块. 这个应该是早就要作的... [mysqld] user = mysql pid-file = /var/run/mysqld/mysqld.pid skip-external-locking old_passwords = 1 skip-bdb skip-innodb users = aa,bb,cc [names] n1 = lzz n2 = orangle n3 = zero e