• Python学习 :常用模块(四)----- 配置文档


    常用模块(四)

    八、configparser 模块

    官方介绍:A configuration file consists of sections, lead by a "[section]" header,and followed by "name: value" entries,

    with continuations and such in the style of RFC 822.

    ConfigParse 模块在 python3 中修改为 configparse ,此模块常用于生成和修改常见配置文档

    Eg.编辑文档的配置文件

    常见的文档格式

    [DEFAULT]
    ServerAliveInterval = 45
    Compression = yes
    CompressionLevel = 9
    ForwardX11 = yes
    
    [bitbucket.org]
    User = hg
    
    [topsecret.server.com]
    Port = 50022
    ForwardX11 = no
    

    根据文档的格式要求来生成文件

    import configparser
    
    config = configparser.ConfigParser()
    # 进行文件配置的第一种方式
    config["DEFAULT"] = {'ServerAliveInterval': '45',
                         'Compression': 'yes',
                         'CompressionLevel': '9'}
    
    config['bitbucket.org'] = {'User' : 'hg'}
    
    # 进行文件配置的第二种方式
    config['topsecret.server.com'] = {}
    topsecret = config['topsecret.server.com']
    topsecret['Host Port'] = '50022'  # 在字典中分别添加键值对
    topsecret['ForwardX11'] = 'no'  
    
    config['DEFAULT']['ForwardX11'] = 'yes'  # 为第一个字典添加键值对
    with open('example.ini', 'w') as configfile:
        config.write(configfile)
    

    configparse 模块的相关操作

    工作方式:先把配置文件读取出来,放入一个对象中再进行相应的操作

    import configparser
    
    # 把配置文件放入一个对象中,进行读取操作
    config = configparser.ConfigParser()
    config.read('example.ini')
    # 浏览配置文件中的内容
    print(config.sections())
    >>> ['bitbucket.org', 'topsecret.server.com']
    print(config.defaults()) # defaults 为特殊的单元,需要单独进行操作
    >>> OrderedDict([('compressionlevel', '9'), ('serveraliveinterval', '45'), ('compression', 'yes'), ('forwardx11', 'yes')])
    
    # 对配置文件进行取值
    print(config['bitbucket.org']['User'])
    for key in config['bitbucket.org']: print(key) # default为特殊的单元,无论对谁进行打印它都会跟着
    >>> hg
        user
        compressionlevel
        serveraliveinterval
        compression
        forwardx11
    
    # 删除数据的两种方法
    config.remove_section('topsecret.server.com')
    config.remove_option('bitbucket.org','user')
    
    config.set('bitbucket.org','user','Mike')
    print(config.has_section('topsecret.server.com'))
    >>> False
    
    # 修改数据
    config.write(open('example.ini', "w"))  # 文件一旦写入后不能修改,此操作为重新创建一个名字相同文件,并进行相应的增加、删除、修改操作
    

     

  • 相关阅读:
    BZOJ 3910 火车 倍增LCA
    CF1012B Chemical table 构造_思维_并查集
    CF 949C Data Center Maintenance_强联通分量_思维题
    CF949B A Leapfrog in the Array 思维题,推理
    关于前端的思考与感悟
    打造专属自己的html5拼图小游戏
    好看的轮播切换效果
    the compatibility problem of ie
    SVG Sprite 入门(SVG图标解决方案)
    Top 15
  • 原文地址:https://www.cnblogs.com/ArticleYeung/p/9869561.html
Copyright © 2020-2023  润新知