读取配置文件
# 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)