configparser 配置模块

读取配置文件


# python3读写配置文件 configparser模块
# configparser是python 内置的解析配置文件的模块
"""
[logging]
lenvel=2
path='/root'
server='login

[mysql]
host:127.0.0.1
port:5000
user:root
password:123456
"""
# 配置文件的格式如上 其中[]表示的section  ,section下的为key-value配置内容。默认支持'='、’:‘两种分割

# 读取文件内容
# #首先初始化实例,并且读取配置文件
# # 然后获得所有的sections,获取section中的keys

#coding=utf-8
import configparser

# 初始化实例
conf=configparser.ConfigParser()
print(type(conf))
print(conf.read('config.ini'))

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

# 获取指定的sections
option=conf.options('mysql')
print('option',option)

# 获取指定的value
value=conf.get('mysql','host')  #根据指定的section和keys来找值
print(value)

# 根据sections获取keys和values
item=conf.items('mysql')
print(item)

# 判断section是否存在
print('log' in conf)

写配置文件


# python3读写配置文件 configparser模块
# configparser是python 内置的解析配置文件的模块
"""
[logging]
lenvel=2
path='/root'
server='login

[mysql]
host:127.0.0.1
port:5000
user:root
password:123456
"""
# 配置文件的格式如上 其中[]表示的section  ,section下的为key-value配置内容。默认支持'='、’:‘两种分割

#coding=utf-8
import configparser

config=configparser.ConfigParser()  #实例化一个对象
config['mysql']={
    'host':'127.0.0.1',
    'port':5000,
    'user':'root',
    'password':123456
}
config['logging']={
    'lenvel':2,
    'path':'root',
    'server':'login'
}

with open('./config.ini','w') as f:
    config.write(f)

修改配置文件


# python3读写配置文件 configparser模块
# configparser是python 内置的解析配置文件的模块
"""
[logging]
lenvel=2
path='/root'
server='login

[mysql]
host:127.0.0.1
port:5000
user:root
password:123456
"""
# 配置文件的格式如上 其中[]表示的section  ,section下的为key-value配置内容。默认支持'='、’:‘两种分割

#coding=utf-8
import configparser

config=configparser.ConfigParser() #首先实例化一个对象
config.read('config.ini')
# 打印所有的section
print(config.sections())
# 根据sections打印key 和value
print((config.items('mysql')))

if 'data' not in config:
    # 添加一个section
    config.add_section('data')
    # 添加keys和值
    config.set('data', 'dataset', 'train.txt')

# 删除一个section
config.remove_section('data')

# 删除一个配置项
config.remove_option('mysql','host')


with open('config.ini','w') as f:
    config.write(f)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一壶浊酒..

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值