zoukankan      html  css  js  c++  java
  • configparser模块--配置文件

    该模块适用于配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。

    创建文件

    import configparser
    
    config = configparser.ConfigParser()
    
    config["DEFAULT"] = {'ServerAliveInterval': '45',
                          'Compression': 'yes',
                         'CompressionLevel': '9',
                         'ForwardX11':'yes'
                         } #DEFAULT是默认分组,名称必须是DEFAULT
    
    config['bitbucket.org'] = {'User':'hg'} # 每一个config[]是一个组
    
    config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'}
    
    with open('example.ini', 'w') as configfile:
    
       config.write(configfile)

    执行结果-'example.ini'文件内容

    [DEFAULT]
    serveraliveinterval = 45
    compression = yes
    compressionlevel = 9
    forwardx11 = yes
    
    [bitbucket.org]
    user = hg
    
    [topsecret.server.com]
    host port = 50022
    forwardx11 = no
    文件内容

    查找文件
    向字典一样操作

    import configparser
    config = configparser.ConfigParser() # 需要先创建对象
    config.read('example.ini') # 给对象绑定配置文件
    print(config.sections()) #  ['bitbucket.org', 'topsecret.server.com'] 返回配置文件中节序列-组名(不包含默认分组)
    
    print('bitbucket.org' in config) # False 判断某个分组是不是在文件里
    print(config['bitbucket.org']["user"])  # hg 查看某组的某项
    print(config['bitbucket.org']["compressionlevel"])  # 9 默认组的内容被其他组共享
    print(config['topsecret.server.com']['ForwardX11'])  # no 当子组中存在与默认组相同的项时,子组查询会使用子组内容
    print(config['bitbucket.org']) # <Section: bitbucket.org>
    for key in config['bitbucket.org']:     # 注意,有default组会打印default组的键,子组优先
        print(key)
    print(config.options('bitbucket.org'))  # 同for循环,找到'bitbucket.org'下所有键,返回一个列表
    print(config.items('bitbucket.org'))    #找到'bitbucket.org'下所有键值对,键值对以元组形式返回,存放在列表里
    print(config.get('bitbucket.org','compression')) # yes       get方法Section下的key对应的value

    增删改操作

    import configparser
    config = configparser.ConfigParser() # 需要先创建对象
    config.read('example.ini') # 给对象绑定配置文件
    
    # config.add_section('yuan') # 增加一个组
    # config.remove_section('bitbucket.org') # 删除一个组
    # config.remove_option('topsecret.server.com',"forwardx11") # 删除一个组中的一项
    # config.set('topsecret.server.com','compression','yes') #给一个组中增加或更改一项,
    
    config.write(open('example.ini', "w")) # 把修改后的内容写会文件才会生效
    

      

  • 相关阅读:
    javascript 显示类型转换
    javascript 隐式类型转换
    inline/inline-block/block 的区别
    javascript 类型检测
    title与h1的区别、b与strong的区别、i与em的区别?
    CSS定位方式有哪些?position属性的值有哪些?他们之间的区别是什么?
    列出display的值,说明他们的作用。position的值, relative和 absolute定位原点是?
    语义化的理解
    src与href的区别
    img的alt和title的异同?
  • 原文地址:https://www.cnblogs.com/wwg945/p/8016733.html
Copyright © 2011-2022 走看看