zoukankan      html  css  js  c++  java
  • python_89_configparser模块

    用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。在python2.x版本中为ConfigPsresr

    来看一个好多软件的常见文档格式如下

    [DEFAULT]
    serveraliveinterval = 45
    compression = yes
    compressionlevel = 9
    forwardx11 = yes
    
    [bitbucket.org]
    user = hg
    
    [topsecret.server.com]
    host port = 50022
    forwardx11 = no
    View Code

    如果想用python生成一个这样的文档怎么做呢?

    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'
    topsecret['ForwardX11'] = 'no'
    
    config['DEFAULT']['ForwardX11'] = 'yes'
    
    with open('example.ini','w') as configfile:
        config.write(configfile)
    

    写完了还可以再读出来

    import configparser
    config=configparser.ConfigParser()#生成一个处理对象
    config.read('example.ini')
    print(config.defaults())
    print(config.sections())
    print('bitbucket.org' in config)
    print('bytebong.com' in config)
    print(config['bitbucket.org'])
    print(config['bitbucket.org']['user'])
    topsecret=config['topsecret.server.com']
    print(topsecret['ForwardX11'])
    for key in config['topsecret.server.com']: print(key)
    
    import configparser
    config=configparser.ConfigParser()#生成一个处理对象
    config.read('example.ini')
    options = config.options('topsecret.server.com')
    print(options)
    item_list = config.items('DEFAULT')
    print(item_list)
    val=config.get('bitbucket.org','user')
    print(val)
    

    configparser增删改查语法

    import configparser
    config=configparser.ConfigParser()#生成一个处理对象
    config.read('example.ini')
    
    sec=config.remove_section('bitbucket.org')
    config.write(open('example1.cfg', "w"))
    
    print(config.has_section('topsecret.server.com'))
    print(config.has_section('server.com'))
    
    sec=config.add_section('wupeiqi')
    config.write(open('example2.cfg', "w"))
    
    config.remove_option('topsecret.server.com','forwardx11')
    config.write(open('example3.cfg', "w"))
    

    http://www.cnblogs.com/ming5218/p/7965973.html

  • 相关阅读:
    appium 多线程还是多进程(转)
    清理不可用的模拟器
    ios-元素查看器安装
    Linux 一条命令杀死占用端口的所有进程
    appium 小程序自动化测试
    (转)MitmProxy+APPnium安装使用
    mysql死锁分析
    母线故障跳闸的处理方法(转载)
    电动葫芦使用注意事项(转载)
    三菱plc输出指示灯不亮怎么办(转载)
  • 原文地址:https://www.cnblogs.com/tianqizhi/p/8452371.html
Copyright © 2011-2022 走看看