Python模块-configparse模块
configparse模块用来解析配置文件
配置文件
[DEFAULT] port = 3306 socket = /tmp/mysql.sock [mysqldump] max_allowed_packet = 16M [myisamchk] key_buffer_size = 256M sort_buffer_size = 256M read_buffer = 2M write_buffer = 2M
读取解析配置文件
# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"
 
import configparser
 
config = configparser.ConfigParser()
 
config.read('config.ini') #读取配置文件,并赋给config
 
print(config.sections())  #读取配置文件中sections的标题,但是没有读取默认的section
print(config.default_section) #读取默认的section
 
print('myisamchk' in config) #判断section是否在配置文件里,返回布尔类型
 
print(list(config['myisamchk'].keys())) #读取指定section和默认section里的option
 
print(config['myisamchk']['read_buffer']) #获取section里option的值
 
print('read_buffer' in config['myisamchk']) #判断option是否在section中
 
#获取指定section和默认section里的option和option的值
for k,v in config['myisamchk'].items():
    print(k,v)
运行结果

删除添加修改等操作
# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
print(config.has_section('python')) #判断section是否在配置文件中
config.add_section('python') #添加section到配置文件中
config.set('python','abc','123c') #给section中的option设置值,如果没有将创建
config.remove_option('python','abc') #删除option
config.remove_section('python') #删除section
config.write(open('config_1.ini', "w")) #要重新写入才能成功完成操作
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号