python的ConfigParser模块_python configpareser

方法描述
read(filenames)filesnames是一个列表,需要从文件加载初始值的应用程序应该在调用read()之前使用readfp()加载所需的文件或文件。
readfp(fp[, filename])在fp中,从文件或文件类对象中读取和解析配置数据(只使用readline()方法)。如果文件名被省略,并且fp有一个name属性,它被用于文件名;默认值为< ? >。

写入配置文件

方法描述
write(fileobject)将配置的表示写入指定的文件对象。这个表示可以由未来的read()调用解析。
对内存中数据流的操作

增加配置文件中的值

方法描述
add_section(section)向实例添加一个section

删除配置文件中的值

方法描述
remove_option(section, option)从指定的部分中删除指定的选项。如果该部分不存在,请提出NoSectionError。如果存在的选项被删除,返回True;否则返回False。
remove_section(section)从配置中删除指定的section。如果这个部分确实存在,返回True。否则返回假

修改配置文件中的值

方法描述
set(section, option, value)如果给定的部分存在,将给定的选项设置为指定的值
optionxform(option)也可以在一个实例上重新设置它,对于一个需要字符串参数的函数。例如,将其设置为str,将使选项名称区分大小写

查找配置文件中的值

方法描述
defaults()返回包含实例范围默认值的字典。
sections()返回可用的section的列表;默认section不包括在列表中
has_section(section)指示指定的section是否出现在配置中。默认的section未被确认
options(section)返回指定section中可用的选项列表。
has_option(section, option)如果给定的section存在,并且包含给定的选项,则返回True;否则返回False
get(section, option)为指定的section获取一个选项值。
getint(section, option)它将指定section中的选项强制转换为整数
getfloat(section, option)它将指定section中的选项强制转换为浮点型
getboolean(section, option)强制转换为布尔型,”1”, “yes”, “true”, and “on”, 转换为True,”0”, “no”, “false”, and “off”, 转换为Falseo 其他返回ValueError.
items(section)返回给定section中每个选项的(name,value)对的列表。
方法描述
import ConfigParser, os

config = ConfigParser.ConfigParser()
config.readfp(open('defaults.cfg'))
config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')])

cfgparser = ConfigParser()
...
cfgparser.optionxform = str

ConfigParser对象

SafeConfigParser中包含ConfigParser相同的方法,还有一部分增加的方法

方法描述
get(section, option[, raw[, vars]])为指定的section获取一个选项值。如果提供了vars,它必须是一个字典。该选项在vars(如果提供)、分段和默认值中查找,
items(section[, raw[, vars]])返回给定section中每个选项的(名称、值)对的列表

所有的“%”插值都在返回值中展开,除非原始的参数是真的。内插键的值与选项相同

SafeConfigParser对象

set(section, option, value)
如果给定的部分存在,将给定的选项设置为指定的值;否则提高NoSectionError。值必须是字符串(str或unicode);如果没有,则会出现类型错误

实例
实例一:写配置文件
import ConfigParser

config = ConfigParser.RawConfigParser()

# When adding sections or items, add them in the reverse order of
# how you want them to be displayed in the actual file.
# In addition, please note that using RawConfigParser's and the raw
# mode of ConfigParser's respective set functions, you can assign
# non-string values to keys internally, but will receive an error
# when attempting to write to a file or when you get it in non-raw
# mode. SafeConfigParser does not allow such assignments to take place.
config.add_section('Section1')
config.set('Section1', 'an\_int', '15')
config.set('Section1', 'a\_bool', 'true')
config.set('Section1', 'a\_float', '3.1415')
config.set('Section1', 'baz', 'fun')
config.set('Section1', 'bar', 'Python')
config.set('Section1', 'foo', '%(bar)s is %(baz)s!')

# Writing our configuration file to 'example.cfg'
with open('example.cfg', 'wb') as configfile:
    config.write(configfile)

实例二:读配置文件
import ConfigParser

config = ConfigParser.RawConfigParser()
config.read('example.cfg')

# getfloat() raises an exception if the value is not a float
# getint() and getboolean() also do this for their respective types
a_float = config.getfloat('Section1', 'a\_float')
an_int = config.getint('Section1', 'an\_int')
print a_float + an_int

# Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
# This is because we are using a RawConfigParser().
if config.getboolean('Section1', 'a\_bool'):
    print config.get('Section1', 'foo')

实例三:获取插入值
import ConfigParser

config = ConfigParser.ConfigParser()
config.read('example.cfg')

# Set the third, optional argument of get to 1 if you wish to use raw mode.
print config.get('Section1', 'foo', 0) # -> "Python is fun!"
print config.get('Section1', 'foo', 1) # -> "%(bar)s is %(baz)s!"

# The optional fourth argument is a dict with members that will take
# precedence in interpolation.
print config.get('Section1', 'foo', 0, {'bar': 'Documentation',
 'baz': 'evil'})

实例四:默认值

所有三种类型的config分析器都可以使用默认值。如果在其他地方没有定义一个选项,那么它们就被用于插值

import ConfigParser

# New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
config = ConfigParser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
config.read('example.cfg')

print config.get('Section1', 'foo')  # -> "Python is fun!"
config.remove_option('Section1', 'bar')
config.remove_option('Section1', 'baz')
print config.get('Section1', 'foo')  # -> "Life is hard!"

实例五:在各section之间移动选项
def opt\_move(config, section1, section2, option):
    try:
        config.set(section2, option, config.get(section1, option, 1))
    except ConfigParser.NoSectionError:
        # Create non-existent section
        config.add_section(section2)
        opt_move(config, section1, section2, option)
    else:
        config.remove_option(section1, option)

实例六:配置文件中有空值

一些配置文件包含了没有值的设置,但是它与ConfigParser支持的语法相一致。对构造函数的不允许值参数可以被用来表示应该接受这样的值

### 一、Python所有方向的学习路线

Python所有方向路线就是把Python常用的技术点做整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。



![](https://img-blog.csdnimg.cn/img_convert/9f49b566129f47b8a67243c1008edf79.png)



### 二、学习软件

工欲善其事必先利其器。学习Python常用的开发软件都在这里了,给大家节省了很多时间。



![](https://img-blog.csdnimg.cn/img_convert/8c4513c1a906b72cbf93031e6781512b.png)



### 三、入门学习视频



我们在看视频学习的时候,不能光动眼动脑不动手,比较科学的学习方法是在理解之后运用它们,这时候练手项目就很适合了。



![](https://img-blog.csdnimg.cn/afc935d834c5452090670f48eda180e0.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA56iL5bqP5aqb56eD56eD,size_20,color_FFFFFF,t_70,g_se,x_16#pic_center)




**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**

**[需要这份系统化学习资料的朋友,可以戳这里无偿获取](https://bbs.csdn.net/topics/618317507)**

**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值