美文网首页
configparser

configparser

作者: 仙灵儿 | 来源:发表于2019-02-27 22:58 被阅读0次
    #类似这样的配置文件,一块一块的分类
    [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'] = {}
    config['bitbucket.org']['User'] = 'hg'
    config['topsecret.server.com'] = {}
    topsecret = config['topsecret.server.com']
    topsecret['Host Port'] = '50022'     # mutates the parser
    topsecret['ForwardX11'] = 'no'  # same here
    config['DEFAULT']['ForwardX11'] = 'yes'
    with open('example.ini', 'w') as configfile:
       config.write(configfile)
    
    #读
    # import configparser
    # config = configparser.ConfigParser()
    # config.sections()
    # 
    # config.read('example.ini')
    # 
    # print(config.defaults())
    # >>>OrderedDict([('compressionlevel', '9'), ('compression', 'yes'), ('serveraliveinterval', '45'), ('forwardx11', 'yes')])
    # print(config['bitbucket.org']["User"])
    # >>>hg
    # print(config["topsecret.server.com"]["host port"])
    # 50022
    
    #删除(创建一个新文件,并删除bitbucket.org)
    import configparser
    config = configparser.ConfigParser()
    config.sections()
    
    config.read('example.ini')
    rec = config.remove_section("bitbucket.org")#删除该项
    config.write(open("example.cfg","w"))
    [DEFAULT]
    compressionlevel = 9
    compression = yes
    serveraliveinterval = 45
    forwardx11 = yes
    
    [topsecret.server.com]
    host port = 50022
    forwardx11 = no
    

    相关文章

      网友评论

          本文标题:configparser

          本文链接:https://www.haomeiwen.com/subject/zczquqtx.html