• Python标准库之ConfigParser模块


    ConfigParser模块用于生成和修改常见配置文档。

    比如配置文件格式如下:

    [DEFAULT]
    ServerAliveInterval = 45
    Compression = yes
    CompressionLevel = 9
    ForwardX11 = yes
     
    [bitbucket.org]
    User = hg
     
    [topsecret.server.com]
    Port = 50022
    ForwardX11 = no

    生成一个配置文件

    import configparser
    
    cfp = configparser.ConfigParser()
    
    cfp['DEFAULT'] = {'ServerAliveInterval':'45','Compression':'yes','CompressionLevel':'9','ForwardX11':'yes'}
    cfp['bitbucket.org'] = {'User':'hg'}
    cfp['topsecret.server.com'] = {'Port':'50022','ForwardX11':'no'}
    
    with open("test.ini",'w') as confile:
    	cfp.write(confile)
    

      

    运行后,在当前目录下生成了一个test.ini文件,文件内容如下:

    读配置文件

    defaults返回的是元组类型。

    import configparser

    cfp = configparser.ConfigParser()

    cfp.read("test.ini")
    print(cfp.defaults())
    print(cfp.sections())
    print(cfp['bitbucket.org']['user'])

     运行结果如下:

    遍历读取

    import configparser
    
    cfp = configparser.ConfigParser()
    
    
    cfp.read("test.ini")
    for i in cfp.defaults():
    	print(i,cfp.defaults()[i])
    

      运行结果:

     

    增删

    删section

    cfp.read("test.ini")
    sec = cfp.remove_section('bitbucket.org')
    cfp.write(open('test.ini', "w"))
    

      

    删option:

    cfp.read("test.ini")
    sec = cfp.remove_option('topsecret.server.com','port')
    cfp.write(open('test.ini', "w"))
    

      

    增section:

    cfp.read("test.ini")
    sec = cfp.add_section('xxxx.server.com')
    cfp.write(open('test.ini', "w"))
    

      

    增option:

    cfp.read("test.ini")
    sec = cfp.set('topsecret.server.com','port',"5002")
    cfp.write(open('test.ini', "w"))
    

      

  • 相关阅读:
    CentOS yum 源的配置与使用
    在css当中使用opacity
    CSS position属性absolute relative等五个值的解释
    uni APP 微信小程序获取授权的微信信息
    vue-admin-element 打包发布后IE报错的问题
    RMAN恢复数据文件
    怎么删除表空间对应的某一个数据文件
    Oracle存储过程、函数、包加密wrap
    Oracle加密解密
    Interval 用法总结
  • 原文地址:https://www.cnblogs.com/endust/p/12312456.html
Copyright © 2020-2023  润新知