python的配置文件ini_python_配置文件_config.ini

本文介绍了Python的ConfigParser模块用于读取ini配置文件的方法,包括获取分类名、选项名、所有键值对以及特定键的字符串和整型值。ConfigParser简单易懂,但灵活性不足,输出格式单一,适用于小型配置文件。需要注意的是,配置文件由节、键、值组成,所有输出默认为字符串,整型需手动转换。
摘要由CSDN通过智能技术生成

be3a86a485ca?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

ConfigParser模块

引用ConfigParser模块做读取配置文件,通过5种方法的叠加遍历使用,能达到读取ini文件的内容;

优点:书写简单容易理解

缺点:不够灵活,输出格式单一,容易给自己挖坑

import ConfigParser

class Read_config:

''' 读取配置文件的各种方法 '''

cf = ConfigParser.ConfigParser()

@classmethod

def return_category(cls, config_file_path):

''' 返回分类名,即[]中的内容 '''

cf = cls.cf

cf.read(config_file_path)

sent = cf.sections()

return sent

@classmethod

def return_options(cls, category, config_file_path):

''' 返回分类中键的名称 '''

cf = cls.cf

cf.read(config_file_path)

opts = cf.options(category)

return opts

@classmethod

def return_items(cls, category, config_file_path):

''' 返回分类中所有内容,以字典形式 '''

cf = cls.cf

cf.read(config_file_path)

kvs = cf.items(category)

return kvs

@classmethod

def return_specific_str(cls, category, keys, config_file_path):

''' 返回指定分类中的指定键的:键值 ---字符串类型 '''

cf = cls.cf

cf.read(config_file_path)

specific = cf.get(category, keys)

return specific

@classmethod

def return_specific_int(cls, category, keys, config_file_path):

''' 返回指定分类中的指定键的:键值 ---整型 '''

cf = cls.cf

cf.read(config_file_path)

specific = cf.getint(category, keys)

return specific

config.ini文件实例

[url]

baidu = https://www.baidu.com

[value]

send_value = 百度

总结

.ini配置文件由节、键、值组成;

设置参数形式为 key:value

.ini文件不时候做大型配置文件使用

注意:输出内容全部为字符串,某些int类型的自己需要转换下;

@晴--2016-09-28 16:48:58

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值