zoukankan      html  css  js  c++  java
  • Python ConfigParser 模块

    用于生成和修改常见配置文档

    import configparser
    
    config = configparser.ConfigParser()
    config["DEFAULT"] = {'ServerAliveInterval': '45',   # 方法一:增加一个 default setion
                         'Compression': 'yes',
                         'CompressionLevel': '9'}
    
    config['klvchen.com'] = {}                          # 方法二:增加一个 klvchen.com setion
    config['klvchen.com']['User'] = 'kl'
    
    config['topsecret.server.com'] = {}                 # 方法三:添加一个 topsecret.server.com
    topsecret = config['topsecret.server.com']
    topsecret['Host Port'] = '50022'     
    topsecret['ForwardX11'] = 'no'  
    
    with open('example.ini', 'w') as configfile:
       config.write(configfile)
    
    

    在当前目录下生成 example.ini 文档:

    [DEFAULT]
    compressionlevel = 9
    compression = yes
    serveraliveinterval = 45
    
    [klvchen.com]
    user = kl
    
    [topsecret.server.com]
    host port = 50022
    forwardx11 = no
    

    常见的操作

    import configparser
    config = configparser.ConfigParser()
    config.read('example.ini')
    
    # 获取 DEFAULT 的键值
    print(config.defaults())
    运行结果:
    OrderedDict([('compressionlevel', '9'), ('compression', 'yes'), ('serveraliveinterval', '45')])
    
    
    # 获取除 DEFAULT 外的 setion
    print(config.sections()) 
    运行结果: ['bitbucket.org', 'topsecret.server.com']
    
    
    # 判断 setion 是否存在
    print('klvchen.com' in config)
    运行结果: True
    
    print(config.has_section('klvchen.com'))
    运行结果: True
    
    
    # 获取 setion 中的某个键值
    print(config['klvchen.com']['User'])
    运行结果: kl
    
    print(config['DEFAULT']['compression'])
    运行结果: yes
    
    
    # 获取所有的 setion,包括 default
    for key in config:
        print(key)
    运行结果:
    DEFAULT
    klvchen.com
    topsecret.server.com
    
    
    # 删除setion
    config.remove_section('topsecret.server.com')  # 整个setion下的键值对都会删除
    config.write(open('example.ini', 'w'))         # 需要重新写入文件
    
    
    # klvchen.com setion 下修改键值,没有即添加 
    config.set('klvchen.com', 'age', '28')
    config.write(open('example.ini', 'w'))         # 需要重新写入文件
    
  • 相关阅读:
    Linux Shell常用shell命令
    shell ls
    [转]推荐一些不错的计算机书籍
    What does it mean when you assign [super init] to self?
    保存,读取与多任务处理
    程序媛去过的地方
    读取pcap文件,过滤非tcp包,获取IP及tcp端口信息
    IM实现联系人及联系人分组的数据库设计
    【原创】校园网用户,1个账号2个笔记本上网,Ad hoc无线连网应用
    【openfire插件开发】群组聊天中的中介者模式
  • 原文地址:https://www.cnblogs.com/klvchen/p/8881504.html
Copyright © 2011-2022 走看看