• 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")) #要重新写入才能成功完成操作
    
  • 相关阅读:
    iOS万能跳转界面的方法
    CocoaPods版本更新
    iOS--开发小技巧(持续更新)
    RunTime--手势应用场景(很方便)
    牛逼的标签效果(封装好)
    直播点赞动画
    UI基础--自定义UISwitch
    StatusBar 更改状态栏颜色(ios7)
    ios版本更新提示
    IOS 两个UIImage 合成一个Image
  • 原文地址:https://www.cnblogs.com/sch01ar/p/8446641.html
Copyright © 2020-2023  润新知