python读取配置文件获取所有键值对_python读写修改配置文件(ini)

示例ini配置文件(setting.ini)

[txtA]

name = comma,end,full,run

comma = 1000

end = 3

full = 2

run = 1

default_comma = 3

default_end = 3

default_full = 2

default_run = 1

[txtB]

name = comma,end,full,run

comma = 1000

end = 3

full = 2

run = 1

default_comma = 3

default_end = 3

default_full = 2

default_run = 1

[chinese]

name = volume,tones,speed,spokesman

volume = 5

tones = 5

speed = 5

spokesman = 1

default_volume = 5

default_tones = 5

default_speed = 5

default_spokesman = 1

[english]

name = volume,tones,speed,spokesman

volume = 5

tones = 5

speed = 5

spokesman = 1

default_volume = 5

default_tones = 5

default_speed = 5

default_spokesman = 1

[help]

[about]

示例ini配置文件操作程序1:

使用configparser函数,缺点:增删、修改都是重写ini文件操作

import configparser

import os

# *** 初始化配置文件路径 *** #

curpath = os.path.dirname(os.path.realpath(__file__)) # 当前文件路径

inipath = os.path.join(curpath, "setting.ini") # 配置文件路径(组合、相对路径)

# *** 数据读取 *** #

conf = configparser.ConfigParser()

conf.read(inipath, encoding="utf-8")

# sections = conf.sections() # 获取所有的sections名称

# options = conf.options(sections[0]) # 获取section[0]中所有options的名称

# items = conf.items(sections[0]) # 获取section[0]中所有的键值对

# value = conf.get(sections[-1],'txt2') # 获取section[-1]中option的值,返回为string类型

# value1 = conf.getint(sections[0],'comma') # 返回int类型

# value2 = conf.getfloat(sections[0],'end') # 返回float类型

# value3 = conf.getboolean(sections[0],'run') # 返回boolen类型

# *** 删除内容 *** #

# conf.remove_option(sections[0], "comma")

# conf.remove_section(sections[1])

# *** 修改内容 *** #

conf.set('txtB', "comma", "1000")

conf.write(open(inipath, "r+", encoding="utf-8")) # r+模式

# print(conf.items(sections[0]) )

示例ini配置文件操作程序2:

使用configobj 函数

from configobj import ConfigObj

# *** 配置文件预处理 *** #

config = ConfigObj("setting.ini",encoding='UTF8')

# *** 读配置文件 *** #

# print(config['txtB'])

# print(config['txtB']['name'])

# *** 修改配置文件 *** #

# config['txtB']['comma'] = "Mufasa"

# config.write()

# *** 添加section *** #

# config['txtC'] = {}

# config['txtC']['index0'] = "wanyu00"

# config.write()

标签:配置文件,python,config,default,comma,ini,conf,sections

来源: https://www.cnblogs.com/navysummer/p/11658394.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值