Python模块之ConfigParser - 读写配置文件

本文详细介绍了Python的ConfigParser模块,用于读写配置文件。配置文件包括一个或多个section,每个section有自己的option,用[sect_name]表示,键值对以等号或冒号分隔。ConfigParser提供了读取配置信息、获取section和option列表、以及写入配置文件等功能。当涉及Unicode编码时,需要使用codecs模块。此外,还提到了 DEFAULT section 和插值(Interpolation)特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文:http://www.cnblogs.com/victorwu/p/5762931.html

注:从配置文件中读取到的数据格式都为str

配置文件的格式

a) 配置文件中包含一个或多个 section, 每个 section 有自己的 option;

b) section 用 [sect_name] 表示,每个option是一个键值对,使用分隔符 = 或 : 隔开;

c) 在 option 分隔符两端的空格会被忽略掉

d) 配置文件使用 # 和 ; 注释

简单的配置文件样例 myapp.conf
 

# database source
[db]
host = 127.0.0.1
port = 3306
user = root
pass = root

[ssh]
host = 192.168.1.101
user = huey
pass = huey


读取配置文件

 

 

# 实例化 ConfigParser
cp = ConfigParser.SafeConfigParser()
# 加载配置文件
cp.read('myapp.conf')

 

 

 

获取 section 列表、option 键列表和 option 键值元组列表 

 

# 获取配置文件中所有section,返回的结果为list类型
cp.sections() # sections: ['db', 'ssh']
# 获取配置文件中sections=db的option的键
cp.options('db')  # [db]: ['host', 'port', 'user', 'pass']
# 获取配置文件中sections=ssh的键值对
cp.items('ssh') # [('host', '192.168.1.101'), ('user', 'huey'), ('pass', 'huey')]

 


读取指定的配置信息

 

# 判断sectino=db是否存在
cp.has_section('db')
# 判断 section=db 下的option=host 是否存在
cp.has_option('db', 'host')
# 添加 section=new_sect
cp.add_section('new_sect')
# 读取指定的配置信息
cp.get('db', 'host') # db: 127.0.0.1
# 设置 section=db下的host=192.168.1.102
cp.set('db', 'host','192.168.1.102')
# 删除 section=db
cp.remove_section('db')
#  删除 section=db下的option=hsot
cp.remove_option('db', 'host')


注:以set、 remove_option、 add_section 和 remove_section 等操作并不会修改配置文件,需要以write 方法将 ConfigParser 对象的配置写到文件中

 

cp.write(open('myapp.conf', 'w'))
cp.write(sys.stdout)

 

Unicode 编码的配置

配置文件如果包含 Unicode 编码的数据,需要使用 codecs 模块以合适的编码打开配置文件

如:配置文件myapp.conf

 

[msg]
hello = 你好


调用文件config_parser_unicode.py

 

 

 

import ConfigParser
import codecs

cp = ConfigParser.SafeConfigParser()
with codecs.open('myapp.conf', 'r', encoding='utf-8') as f:
    cp.readfp(f)


print cp.get('msg', 'hello')

 

DEFAULT section

 

 

如果配置文件中存在一个名为 DEFAULT 的 section,那么其他 section 会扩展它的 option 并且可以覆盖它的 option
 

[DEFAULT]
host = 127.0.0.1
port = 3306

[db_root]
user = root
pass = root

[db_huey]
host = 192.168.1.101
user = huey
pass = huey


----------------------------------------------------

 

print cp.get('db_root', 'host')    # 127.0.0.1
print cp.get('db_huey', 'host')    # 192.168.1.101


插值 Interpolation

 

SafeConfigParser 提供了插值的特性来结合数据

 

[DEFAULT]
url = %(protocol)s://%(server)s:%(port)s/

[http]
protocol = http
server = localhost
port = 8080

[ftp]
url = %(protocol)s://%(server)s/
protocol = ftp
server = 192.168.1.102


-------------------------------------------

 

import ConfigParser

cp = ConfigParser.SafeConfigParser()
cp.read('url.conf')

print cp.get('http', 'url')    # http://localhost:8080/
print cp.get('ftp', 'url')     # ftp://192.168.1.102/

 

readconfig.py

# !/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import configparser
import logg

"""
ConfigParser 是用来读取配置文件的包。
配置文件的格式如下:中括号“[ ]”内包含的为section。
section 下面为options = items(类似于key-value) 的配置内容。

[db]
db_host = 127.0.0.1
db_port = 69
db_user = root
db_pass = root
host_port = 69
"""


def r_conf(conf_name, op, **ks):
    # 调用日志
    log = logg.log_input()

    # 获取当前文件所在目录的上一级目录,即项目所在目录
    root_dir = os.path.dirname(os.path.abspath('.'))
    # 拼接配置文件地址
    config_path = os.path.join(root_dir+"/conf/", conf_name)

    # 判断文件是否存在
    if os.path.exists(config_path):
        # 初始化实例
        config = configparser.ConfigParser()
        # 取配置文件
        config.read(config_path, encoding="utf-8")

        if op == 1 or op == "1":
            # 获取所有的section节点
            return config.sections()

        else:
            # 判断 参数中是否存在section
            if 'section' in ks.keys():
                # 判断 配置文件中是否存在section
                if config.has_section(ks["section"]):
                    if op == 2 or op == "2":
                        # 获取指定section 的options,即将配置文件某个section的key
                        r = config.options(ks["section"])
                        return r

                    elif op == 3 or op == "3":
                        # 获取指点section的所用配置信息,即将配置文件某个section 内value
                        r = config.items(ks["section"])
                        return r

                    else:
                        # 判断 参数中是否存在option
                        if 'option' in ks.keys():
                            # 判断 配置文件中是否存在option
                            if config.has_option(ks["section"], ks["option"]):
                                if op == 4 or op == "4":
                                    # 获取指点section下指点option的值
                                    r = config.get(ks["section"], ks["option"])
                                    # r1 = config.getint("db", "k1") #将获取到值转换为int型
                                    return r
                                else:
                                    log.error("op参数仅支持1,2,3,4,请传递指定值!!!")
                            else:
                                log.info(" 配置文件中"+ks["section"]+"下不存在:" + ks["option"])
                        else:
                            log.error("请传指定参数名option,否则不能验证通过!!!")
                else:
                    log.info(conf_name+" 配置文件中不存在:"+ks["section"])
            else:
                log.error("请传指定参数名section,否则不能验证通过!!!")

    else:
        log.error(config_path+" 不存在,请检查后重试!")


if __name__ == '__main__':
    # 获取所有的section(每个section由[]包裹,即[section]),并以列表的形式返回
    print(r_conf('config.ini', 1))
    # 获取某个section名为db所对应的键
    print(r_conf('config.ini', 2, section='db'))
    # 获取section名为db所对应的全部键值对
    print(r_conf('config.ini', 3, section='db'))
    # 获取[db]中db_host对应的值
    print(r_conf('config.ini', 4, section='db', option='db_host'))

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值