zoukankan      html  css  js  c++  java
  • python-26 configparser 模块之一

    ConfigParser Objects:

    class configparser.ConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT, interpolation=BasicInterpolation(), converters={})


    该模块支持读取类似如上格式的配置文件,如 windows 下的 .conf 及 .ini 文件等

    1. defaults():返回一个包含实例范围默认值的词典
    2. sections(): 得到所有的section,并以列表的形式返回
    3. add_section(section):添加一个新的section
    4. has_section(section):判断是否有section
    5. options(section) 得到该section的所有option
    6. has_option(section, option):判断如果section和option都存在则返回True否则False
    7. read(filenames, encoding=None):直接读取配置文件内容
    8. read_file(f, source=None):读取配置文件内容,f必须是unicode
    9. read_string(string, source=’’):从字符串解析配置数据
    10. read_dict(dictionary, source=’’)从词典解析配置数据
    11. get(section, option, *, raw=False, vars=None[, fallback]):得到section中option的值,返回为string类型
    12. getint(section,option) 得到section中option的值,返回为int类型
    13. getfloat(section,option)得到section中option的值,返回为float类型
    14. getboolean(section, option)得到section中option的值,返回为boolean类型
    15. items(raw=False, vars=None)和items(section, raw=False, vars=None):列出选项的名称和值
    16. set(section, option, value):对section中的option进行设置
    17. write(fileobject, space_around_delimiters=True):将内容写入配置文件。
    18. remove_option(section, option):从指定section移除option
    19. remove_section(section):移除section
    20. optionxform(option):将输入文件中,或客户端代码传递的option名转化成内部结构使用的形式。默认实现返回option的小写形式;
    21. readfp(fp, filename=None)从文件fp中解析数据

    基础读取配置文件

    • -read(filename)                 直接读取文件内容
    • -sections()                         得到所有的section,并以列表的形式返回
    • -options(section)              得到该section的所有option
    • -items(section)                  得到该section的所有键值对
    • -get(section,option)         得到section中option的值,返回为string类型
    • -getint(section,option)    得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。

    基础写入配置文件

      • -write(fp)                                                           将config对象写入至某个 .init 格式的文件
      • -add_section(section)                                    添加一个新的section
      • -set( section, option, value                            对section中的option进行设置,需要调用write将内容写入配置文件
      • -remove_section(section)                      删除某个 section
      • -remove_option(section, option)             删除某个 section 下的 option
    • 实例一:
    import configparser
    # 1.创建cofigparser实例
    config=configparser.ConfigParser() #config={},整体相当于一个空字典
    config['DEFAULT']={'ServerAliveInterval' : 45,
                        'Compression':'yes',
                         'CompressionLevel' :9,
                          'ForwardX11' : 'yes'}
    
    with open('sample.ini','w+') as f:
        config.write(f)      # 将对象写入配置文件  congfig.write(fp)                   
    View Code

     

    # 1.创建cofigparser实例
    config=configparser.ConfigParser() #config={},整体相当于一个大的空字典
    config['DEFAULT']={'ServerAliveInterval' : 45,
                        'Compression':'yes',
                         'CompressionLevel' :9,
                          'ForwardX11' : 'yes'}
    
    config['topsecret.server.com'] = {} #设置一个外层大字典的key='topsecret.server.com',val={}
    topsecret = config['topsecret.server.com'] #把key赋给变量topsecret,即topsecret变量是内层一个空字典
    topsecret['Host Port'] = '50022'     # 内层空典设置key='Host Port',val='50022'
    topsecret['ForwardX11'] = 'no'       #  实质是字典嵌套
    
    config['bitbucket.org'] = {}
    config['bitbucket.org']['User'] = 'hg'
    
    #-------------------------字典嵌套整体写入---------------------------------------------------------
    dic={'section1':{'name':'小明','sex':''},
         'section2':{'addr':'北京路','tel':'12345678'}
         }
    config.read_dict(dic) #用read_dict方法写入
    
    with open('sample.ini','w+',encoding='utf-8') as f:
        config.write(f)      # 将对象写入配置文件  congfig.write(fp)
    View Code

     #=============================================查

    cf=configparser.ConfigParser()   #实例化对象
    ls_f=cf.read('sample.ini',encoding='utf-8') #读取配置文件,返回文件名'sample.ini'
    ls_sec=cf.sections()    #获取所有节信息,但不包括【DEFAULT】,list(cf)也是返回所有节信息,包含【DEFAULT】
    print('name:%s
    ist(cf):%s
    l_sec:%s'%(ls_f,list(cf),ls_sec))
    View Code

    for key in cf['topsecret.server.com']: #遍历任何一个section,都包含[DEFAULT]下的option
        print(key)
    
    print(cf.options('topsecret.server.com'))#options取指定section下的key值,包含[DEFAULT]下
    
    print(cf.items('topsecret.server.com'))#items,取指定section下的(key,val)值,包含[DEFAULT]下
    
    print(cf.get('topsecret.server.com','compressionlevel')) #获取指定section下的指定key的值,如果没有去[DEFAULT]下找
    View Code

    #===================================增

    cf.add_section('home')    #增加一个section
    cf.set('home','familyname','zhou')  #增加一个key和val
    
    cf.write(open('sample.ini','a+',encoding='utf-8'))#写入文件
    View Code

    #==================================删除

    cf.remove_section('section2')#删除section
    cf.remove_option('section1','name')#删除section1下的键值对
    View Code

     

    for key in cf['topsecret.server.com']: #遍历任何一个section,都包含[DEFAULT]下的option
        print(key
  • 相关阅读:
    todo--H2数据库
    todo--mybatis-generator-config....
    初次使用git配置以及git如何使用ssh密钥(将ssh密钥添加到github)
    Git 快速入门
    IOS IAP APP内支付 Java服务端代码
    In-App Purchase(iap)快速指南
    Spring MVC @ModelAttribute详解
    Spring MVC @SessionAttributes注解
    Spring MVC 向页面传值-Map、Model和ModelMap
    Spring MVC 向前台页面传值-ModelAndView
  • 原文地址:https://www.cnblogs.com/Zhouzg-2018/p/10258683.html
Copyright © 2011-2022 走看看