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')) #保存到配置文件
  • 相关阅读:
    css3实现轮播2
    css3实现轮播1
    读阮一峰ES6笔记4:字符串的新增方法
    读阮一峰ES6笔记3:字符串的扩展
    应用流策略与检查配置结果
    配置流策略
    配置流行为
    配置流分类
    "流量监管"和"流量整形"的区别
    802.1p 优先级与内部优先级的映射关系
  • 原文地址:https://www.cnblogs.com/cmsd/p/3877761.html
Copyright © 2011-2022 走看看