• python configparser模块


    import configparser
    
    # 创建配置文件
    config = configparser.ConfigParser()  # config={}
    #
    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
    
    with open('example.ini', 'w') as f:
        config.write(f)
    
    # 对配置文件进行操作
    # 读取配置文件
    config.read('example.ini')
    # 读取配置文件模块 ,DEFAULT模块不显示
    ret = config.sections()
    print(ret)  # ['bitbucket.org', 'topsecret.server.com']
    
    print('bytebong.com' in config)  # False
    # 读取模块下的键值
    print(config['bitbucket.org']['User'])  # hg 读取模块下的键值
    print(config['DEFAULT']['Compression'])  # yes
    print(config['topsecret.server.com']['ForwardX11'])  # no
    
    # 在 DEFAULT模块下的键值,其他模块都能获取
    for key in config['bitbucket.org']:
        print(key)
    # 结果
    # user
    # serveraliveinterval
    # compression
    # compressionlevel
    
    # options 获取模块下的所有键名,存入列表,包括DEFAULT模块下的键名
    ret = config.options('bitbucket.org')
    print(ret)
    # ['user', 'serveraliveinterval', 'compression', 'compressionlevel']
    
    # items 获取模块下的所有键值,以元组形式存入列表,包括DEFAULT模块下的键名
    ret = config.items('bitbucket.org')
    print(ret)
    # [('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('user', 'hg')]
    
    # 获取指定模块下的值
    ret = config.get('bitbucket.org', 'compression')
    print(ret)  # yes
    
    # 新增模块
    config.add_section('yuan')
    # 新增键值
    config.set('yuan', 'k1', '11111')
    # 删除模块
    config.remove_section('topsecret.server.com')
    # 删除键值
    config.remove_option('bitbucket.org', 'user')
    # 重新写入配置
    config.write(open('i.cfg', "w"))
  • 相关阅读:
    curl 的使用,参数大全
    ubuntu 编译安装php5扩展
    ubuntu 编译安装 php5.6.40
    ubuntu 编译安装 mysql5.7.32
    ubuntu 编译安装 apache2.4.46
    Android 逆向工具总结
    mariadb 和 mysql 之间的版本关系
    ubuntu 使用 apt 安装 apache2 php7 mysql8
    linux 系统安装 pip
    P2756 飞行员配对方案问题 提交 13.91k 通过 7.59k 时间限制 1.00s 内存限制 125.00MB 返回题目
  • 原文地址:https://www.cnblogs.com/kehaimin/p/11474635.html
Copyright © 2020-2023  润新知