zoukankan      html  css  js  c++  java
  • 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")) #要重新写入才能成功完成操作
    
  • 相关阅读:
    linux 定时备份数据库
    Web前端优化>javascript优化
    IT项目开发的75条管理守则
    Web前端优化>css 优化
    Web前端优化>图象篇
    SNS关键点
    项目管理(对事不对人)
    Yahoo!网站性能最佳体验的34条黄金守则——内容
    互联网主题知名博客
    Web前端优化>Cookie 优化
  • 原文地址:https://www.cnblogs.com/sch01ar/p/8446641.html
Copyright © 2011-2022 走看看