pyhton读取.conf和.ini文件

说明: 这些demo是用于开发时,如果程序要使用配置文件来配合运行可以用这些demo,让我们的程序看起来更加高大上,哈哈哈。。。注意配置文件的后缀。

conf.conf文件:

[info]
name=zhangsan
age=20
class=31班
addr=火星
phone=10086

[score]
yuwen=99
shuxue=99
yingyu=98

[test]
num=13

conf.ini文件:

[info]
name=lisi
age=20
class=32班
addr=水星
phone=10000

[score]
yuwen=98
shuxue=98
yingyu=99

[test]
num=12

python代码:

import configparser


config = configparser.ConfigParser()
config.read("conf.conf", encoding="utf-8")
# 读取info下的name
print(config['info']['name'])
print(config.get('info', 'name'))
# 判断配置文件中是否存在score块
print('score' in config)
# 得到所有的section
print(config.sections())
# 得到该info的所有option
print(config.options('info'))
# 得到该info的所有option和value
print(config.items('score'))
# 修改option
print(config['info']['age'])
config['info']['age'] = '18'
print(config['info']['age'])
# 删除指定的option
config.remove_option('score', 'lishi')
print(config.items('score'))
# 删除指定的section
config.remove_section('test')
# 添加一个section
config.add_section('other')
print(config.sections())
# 设置新section的options
config.set('other', 'height', '180cm')
# 字典方式
config['other'] = {
    'weight': '150kg',
    'power': '100'
}
print(config.items('other'))
# 写回到文件
config.write(open('test.conf', 'w', encoding='UTF-8'), space_around_delimiters=False)

上面的修改分别保存了两个文件:test.conf和test.ini,看下结果吧。
test.conf文件:

[info]
name=zhangsan
age=18
class=31班
addr=火星
phone=10086

[score]
yuwen=99
shuxue=99
yingyu=98

[other]
weight=150kg
power=100


test.ini文件:

[info]
name=lisi
age=18
class=32班
addr=水星
phone=10000

[score]
yuwen=98
shuxue=98
yingyu=99

[other]
weight=150kg
power=100


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值