python configparser 数组_python configparser

# ConfigParserObject.getfloat(section, option)

# 返回结果是float类型

money = config.getfloat('user', 'money')

print(money, type(money)) # 26985.4578 # 检查section或option是否存在, 返回bool值,若存在返回True,不存在返回False

# 检查section是否存在

result = config.has_section('user_name')

print(result) # False

result = config.has_section('user')

print(result) # True

# 检查option是否存在

result = config.has_option('user', 'user_name')

print(result) # True

result = config.has_option('user', 'root')

print(result) # False

# 添加section

# 如果section不存在,则添加节点section;

# 若section已存在,再执行add操作会报错configparser.DuplicateSectionError: Section XX already exists

if not config.has_section('redis'):

config.add_section('redis')

config.set('redis', 'name', '192.168.1.22')

f = open('config.ini', 'w')

config.write(f)

f.close()

redis = config.items('redis')

print(redis) # [('name', '192.168.1.22')], config.ini 会多出来增加的section

# 修改或添加指定节点下指定option的值

# 若option存在,则会替换之前option的值为value, 若option不存在,则会创建option并赋值为value

# 修改指定option的值

config.set('user', 'user_name', 'root')

config.set('user', 'user_name', 'tingfeng')

f = open('config.ini', 'w')

config.write(f)

f.close()

# 重新查看修改后节点信息

items = config.items('user')

print(items) # [('user_name', 'tingfeng'), ('password', '1234'), ('money', '26985.4578')]

# 删除section或option

# ConfigParserObject.remove_section(section)

# 若section存在,执行删除操作,若section不存在,则不会执行任何操作

# 删除section

config.remove_section('user')

config.remove_section('user_name')

all_sections = config.sections()

print(all_sections) # ['connect', 'mysql', 'mysql_connect', 'redis']

# ConfigParserObject.remove_option(section, option)

# 若option存在,执行删除操作,若option不存在,则不会执行任何操作;

# 若section不存在,则会报错configparser.NoSectionError: No section: XXX

# 删除option

config.remove_option('user', 'user_name')

config.remove_option('user', 'user_name')

f = open('config.ini', 'w')

config.write(f)

f.close()

all_sections = config.sections()

print(all_sections) # ['user', 'connect', 'mysql', 'mysql_connect', 'redis']

print(config.options('user')) # ['password', 'money']

# 写入配置文件

# 对configparser对象执行的一些修改操作,必须重新写回到文件才可生效

config.write(open(file_name, 'w'))

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值