zoukankan      html  css  js  c++  java
  • Python之配置文件模块 ConfigParser

    写项目肯定用的到配置文件,这次学习一下python中的配置文件模块 ConfigParser

    安装就不说了,pip一下即可,直接来个实例

    配置文件 project.conf

    [db]
    host = '127.0.0.1'
    port = 3306
    user = 'root'
    password = 'redhat'
    db = 'project'
    
    [app]
    threads = 4
    cache_size = 8M
    
    [game]
    speed = 100

    脚本 project.py

    #!/usr/bin/python
    #coding: utf-8
    
    import ConfigParser
    
    cf = ConfigParser.ConfigParser()
    cf.read('project.conf')
    
    #所有section
    print cf.sections()
    
    #显示某个sections下的选项
    print cf.options('db')
    
    #键值方式显示section的值
    print cf.items('db')
    
    #获得某个section的某个选项的值
    host = cf.get('db', 'host')
    print host
    
    ##get获得是string格式的,下面获得Int格式的和float格式的
    port = cf.getint('db', 'port')
    print port, type(port)
    
    port = cf.getfloat('db', 'port')
    print port, type(port)
    
    ##获得boolean方式的值
    play = cf.getboolean('game', 'play')
    print play
    
    ##添加section
    cf.add_section('redis')
    print cf.sections()
    
    ##添加option
    cf.set('redis', 'host', '127.0.0.1')
    print cf.items('redis')
    
    ##修改option
    cf.set('db', 'host', '192.168.1.1')
    print cf.items('db')
    
    ##保存配置文件
    cf.write(open('project.conf', 'w'))

    总结方法:

    read(filename)   #读取配置文件
    sections()           #返回所有section
    options(section) #返回section中的option
    items(section)    #返回sectiond的键值对
    get(section, option) #返回某个section,某个option的值,类型是string
    getint, getfloat, getboolean 等等返回的只是类型不同
    
    修改配置
    add_section(section)  #添加section
    set(section,option,value) #添加或者修改值
    write(open(filename,'w')) #保存到配置文件
  • 相关阅读:
    移动端轮播图
    移动端的注册页面
    点击显示或者消失的效果(手风琴效果)
    canvas的一些简单绘制方法
    用canvas来手动绘画
    canvas标签的运用
    Html5新标签解释及用法
    最近的心得
    浅谈正则表达式
    P3197 [HNOI2008]越狱
  • 原文地址:https://www.cnblogs.com/cmsd/p/3877761.html
Copyright © 2011-2022 走看看