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

 

猜你喜欢

转载自www.cnblogs.com/Zhouzg-2018/p/10258683.html