configparser 保存_python3.52 使用configparser模块读写ini文件

使用configparser模块读写ini文件,如果是python 2.7 使用为 import ConfigParser,python 3.2 以后的版本中 ,应当使用import configparser。Python的configparser Module中定义了3个类对INI文件进行操作。分别是RawConfigParser、ConfigParser、SafeConfigParser。模块所解析的ini配置文件是由多个section构成,每个section名用中括号‘[]’包含,每个section下可有多个配置项类似于key-value形式,例如:

[sec_a]

a_key1 = 20

a_key2 = 10

[sec_b]

b_key1 = 121

b_key2 = b_value2

b_key3 = abc

b_key4 = 127.0.0.1

configparser模块以ConfigParser类为例,其操作基本分为三类:1)初始化;2)读取配置;3)写入配置。

1. ConfigParser 初始化

使用ConfigParser 首选需要初始化实例,并读取配置文件:

cf = ConfigParser.ConfigParser() cf.read("配置文件名")

2. 基本的读取配置文件

-read(filename) 直接读取ini文件内容

-sections() 得到所有的section,并以列表的形式返回

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

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

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

-getint(section,option) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。

3.基本的写入配置文件

-add_section(section) 添加一个新的section

-set( section, option, value) 对section中的option进行设置,需要调用write将内容写入配置文件。

-write(strout) 将对configparser类的修改写入

ini是微软Windows操作系统中的文件扩展名(也常用在其他系统)。INI是英文“初始化(Initial)”的缩写。正如该术语所表示的,INI文件被用来对操作系统或特定程序初始化或进行参数设置。通过它,可以将经常需要改变的参数保存起来(而且还可读),使程序更加的灵活。

先给出一个ini文件的示例。

[sec_a]

a_key1 = 20

a_key2 = 10

[sec_b]

b_key1 = 121

b_key2 = b_value2

b_key3 = abc

b_key4 = 127.0.0.1

Python代码

>>> import configparser

# 初始化

>>> conf = configparser.ConfigParser()

>>> conf.read("test.ini")['test.ini']

# 获取指定的section, 指定的option的值

>>> name = conf.get("sec_a","a_key1")

>>> print(name)

20

>>> name2 = conf.get("sec_a","a_key2")

>>> print(name2)

10

# 获取所有的section

>>> sections = conf.sections()

>>> print(sections)

['sec_a', 'sec_b']

# 获取该section的所有option的值

>>> print(conf.options("sec_a"))

['a_key1', 'a_key2']

>>> print(conf.options("sec_b"))

['b_key1', 'b_key2', 'b_key3', 'b_key4', 'b_key5']

# 获取该section的所有的键值对

>>> print(conf.items("sec_a"))

[('a_key1', '30'), ('a_key2', '10')]

>>> print(conf.items("sec_b"))

[('b_key1', '121'), ('b_key2', 'b_value2'), ('b_key3', '$r'), ('b_key4', '127.0.0.1')]

# 更新指定section, option的值

>>> conf.set("sec_a", "a_key1", "30")>>> print(conf.get("sec_a","a_key1"))

30# 写入指定section, 增加新option的值

>>> conf.set("sec_b", "b_key5", "123")>>> print(conf.get("sec_b","b_key5"))

123

# 添加新的 section和option的值

>>> conf.add_section("sec_c")>>> conf.set("sec_c","c_key1","123456")

>>> print(conf.sections())

['sec_a', 'sec_b', 'sec_c']

# 修改完之后要记得使用configparser.write()进行写入操作,否则修改的内容不会保存到配置文件

>>> conf.write(open("test.ini","w"))

最后结果如下:

[sec_a]

a_key1 = 30

a_key2 = 10

[sec_b]

b_key1 = 121

b_key2 = b_value2

b_key3 = abc

b_key4 = 127.0.0.1

b_key5 = 123

[sec_c]

c_key1 = 123456

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值