python 网站开发教程,坂田网站建设公司,建设娱乐城网站,做网站业务员如何跟客户沟通目录 
INI文件 
configparser内置库 
类与方法 
操作实例 
导入INI 
查询所有节的列表 
判断某个节是否存在 
查询某个节的所有键的列表 
判断节下是否存在某个键 
增加节点 
删除节点 
增加节点的键 
修改键值 
保存修改结果 
获取键值 
获取节点所有键值 INI文件 
即Initiali… 
目录 
INI文件 
configparser内置库 
类与方法 
操作实例 
导入INI 
查询所有节的列表 
判断某个节是否存在 
查询某个节的所有键的列表 
判断节下是否存在某个键 
增加节点 
删除节点 
增加节点的键 
修改键值 
保存修改结果 
获取键值 
获取节点所有键值 INI文件 
即Initialization File的缩写是Windows系统配置文件所采用的存储格式用于统管Windows的各项配置。虽然Windows 95之后引入了注册表的概念使得许多参数和初始化信息被存储在注册表中但在某些场合INI文件仍然具有其不可替代的地位。 
INI文件是一种按照特殊方式排列的文本文件其格式规范包括节section、键name和值value。节用方括号括起来单独占一行用于表示一个段落区分不同用途的参数区。键也称为属性单独占一行用等号连接键名和键值例如“namevalue”。注释使用英文分号;开头单独占一行分号后面的文字直到该行结尾都作为注释处理。 
INI文件在Windows系统中非常常见其中最重要的是“System.ini”、“System32.ini”和“Win.ini”等文件。这些文件主要存放用户所做的选择以及系统的各种参数。用户可以通过修改INI文件来改变应用程序和系统的很多配置。当然我们自己编写程序时也可以把INI文件作为配置和管理参数的工具比如python中就有内置库configparser可以方便地配置和管理程序的参数。 
configparser内置库 
类与方法 Intrinsic defaults can be specified by passing them into the ConfigParser constructor as a dictionary. class: ConfigParser -- responsible for parsing a list of configuration files, and managing the parsed database. methods: __init__(defaultsNone, dict_type_default_dict, allow_no_valueFalse,                  delimiters(, :), comment_prefixes(#, ;),                  inline_comment_prefixesNone, strictTrue,                  empty_lines_in_valuesTrue, default_sectionDEFAULT,                  interpolationunset, convertersunset): Create the parser. When defaults is given, it is initialized into the dictionary or intrinsic defaults. The keys must be strings, the values must be appropriate for %()s string interpolation. When dict_type is given, it will be used to create the dictionary objects for the list of sections, for the options within a section, and for the default values. When delimiters is given, it will be used as the set of substrings that divide keys from values. When comment_prefixes is given, it will be used as the set of substrings that prefix comments in empty lines. Comments can be indented. When inline_comment_prefixes is given, it will be used as the set of substrings that prefix comments in non-empty lines. When strict is True, the parser wont allow for any section or option             duplicates while reading from a single source (file, string or             dictionary). Default is True. When empty_lines_in_values is False (default: True), each empty line marks the end of an option. Otherwise, internal empty lines of a multiline option are kept as part of the value. When allow_no_value is True (default: False), options without values are accepted; the value presented for these is None. When default_section is given, the name of the special section is named accordingly. By default it is called DEFAULT but this can be customized to point to any other valid section name. Its current value can be retrieved using the parser_instance.default_section attribute and may be modified at runtime. When interpolation is given, it should be an Interpolation subclass instance. It will be used as the handler for option value pre-processing when using getters. RawConfigParser objects dont do any sort of interpolation, whereas ConfigParser uses an instance of BasicInterpolation. The library also provides a zc.buildout inspired ExtendedInterpolation implementation. When converters is given, it should be a dictionary where each key represents the name of a type converter and each value is a callable implementing the conversion from string to the desired datatype. Every converter gets its corresponding get*() method on the parser object and section proxies. sections()             Return all the configuration section names, sans DEFAULT. has_section(section)             Return whether the given section exists. has_option(section, option)             Return whether the given option exists in the given section. options(section)             Return list of configuration options for the named section. read(filenames, encodingNone)             Read and parse the iterable of named configuration files, given by name.  A single filename is also allowed.  Non-existing files are ignored.  Return list of successfully read files. read_file(f, filenameNone)             Read and parse one configuration file, given as a file object.             The filename defaults to f.name; it is only used in error messages (if f has no name attribute, the string ??? is used). read_string(string)             Read configuration from a given string. read_dict(dictionary)             Read configuration from a dictionary. Keys are section names, values are dictionaries with keys and values that should be present in the section. If the used dictionary type preserves order, sections and their keys will be added in order. Values are automatically converted to strings. get(section, option, rawFalse, varsNone, fallback_UNSET)             Return a string value for the named option.  All % interpolations are expanded in the return values, based on the defaults passed into the constructor and the DEFAULT section.  Additional substitutions may be provided using the vars argument, which must be a dictionary whose contents override any pre-existing defaults. If option is a key in vars, the value from vars is used. getint(section, options, rawFalse, varsNone, fallback_UNSET)             Like get(), but convert value to an integer. getfloat(section, options, rawFalse, varsNone, fallback_UNSET)             Like get(), but convert value to a float. getboolean(section, options, rawFalse, varsNone, fallback_UNSET)             Like get(), but convert value to a boolean (currently case insensitively defined as 0, false, no, off for False, and 1, true, yes, on for True).  Returns False or True. items(section_UNSET, rawFalse, varsNone)             If section is given, return a list of tuples with (name, value) for each option in the section. Otherwise, return a list of tuples with (section_name, section_proxy) for each section, including DEFAULTSECT. remove_section(section)             Remove the given file section and all its options. remove_option(section, option)             Remove the given option from the given section. set(section, option, value)             Set the given option. write(fp, space_around_delimitersTrue)             Write the configuration state in .ini format. If space_around_delimiters is True (the default), delimiters between keys and values are surrounded by spaces. 
操作实例 
就以我电脑上的win.ini的内容作操作对象为防止乱改windows参数把win.ini复制到源代码目录中并改名为exam.ini。 ; for 16-bit app support [fonts] [extensions] [mci extensions] [files] [Mail] MAPI1 导入INI import configparser  parser  configparser.ConfigParser()  parser.read(exam.ini) [exam.ini] 
查询所有节的列表 parser.sections() [fonts, extensions, mci extensions, files, Mail] 
判断某个节是否存在 parser.has_section(fonts) True  parser.has_section(font) False  parser.has_section(files) True 
查询某个节的所有键的列表 parser.options(Mail) [mapi]  parser.options(mail) Traceback (most recent call last):   File pyshell#21, line 1, in module     parser.options(mail)   File D:\Program Files\Python\Lib\configparser.py, line 661, in options     raise NoSectionError(section) from None configparser.NoSectionError: No section: mail  parser.options(files) []  parser.options(Files) Traceback (most recent call last):   File pyshell#31, line 1, in module     parser.options(Files)   File D:\Program Files\Python\Lib\configparser.py, line 661, in options     raise NoSectionError(section) from None configparser.NoSectionError: No section: Files 
注意节名区别字母大小写。 
判断节下是否存在某个键 parser.has_option(Mail,mapi) True  parser.has_option(Mail,Mapi) True  parser.has_option(Mail,MAPI) True  parser.has_option(Mail,abc) False  parser.has_option(Mail,ABC) False 
注意键名不区别字母大小写。 
增加节点 parser.add_section(Names)  parser.sections() [fonts, extensions, mci extensions, files, Mail, Names]  parser.add_section(names)  parser.sections() [fonts, extensions, mci extensions, files, Mail, Names, names] 
注意增加已在节会抛错DuplicateSectionError(section) parser.add_section(names) Traceback (most recent call last):   File pyshell#47, line 1, in module     parser.add_section(names)   File D:\Program Files\Python\Lib\configparser.py, line 1189, in add_section     super().add_section(section)   File D:\Program Files\Python\Lib\configparser.py, line 645, in add_section     raise DuplicateSectionError(section) configparser.DuplicateSectionError: Section names already exists 
正确用法配合has_section()一起使用 if not parser.has_section(Level): ...     parser.add_section(Level) ...   parser.sections() [fonts, extensions, files, Mail, names, Level] 
删除节点 parser.sections() [fonts, extensions, mci extensions, files, Mail, Names, names]  parser.remove_section(Names) True  parser.remove_section(file) False  parser.remove_section(mci extensions) True  parser.sections() [fonts, extensions, files, Mail, names] 
注意是否删除成功由返回值True或False来判断。 
增加节点的键 parser.options(Mail) [mapi]  if not parser.has_option(Mail, names): ...     parser.set(Mail, names, ) ...  ...       parser.options(Mail) [mapi, names] 
修改键值 
与增加键一样用set()但value参数不为空。 parser.set(Mail, names, Hann) 
或者写成 
parser.set(sectionMail, optionnames, valueHann) 
保存修改结果 parser.write(fpopen(exam.ini, w)) 
注意增删等改变ini文件内容的操作都要write才能得到保存。 
获取键值 parser.get(Mail, names) Hann  parser.get(Mail, Names) Hann  parser.get(mail, Names) Traceback (most recent call last):   File pyshell#81, line 1, in module     parser.get(mail, Names)   File D:\Program Files\Python\Lib\configparser.py, line 759, in get     d  self._unify_values(section, vars)   File D:\Program Files\Python\Lib\configparser.py, line 1130, in _unify_values     raise NoSectionError(section) from None configparser.NoSectionError: No section: mail 
注意再次证明节名区别大小写键名不区别大小写。 
获取节点所有键值 parser.items(Mail) [(mapi, 1), (name, Hann), (names, Tom), (kates, )] 
完整示例代码 
import configparser  # 创建一个配置解析器  
parser  configparser.ConfigParser()  # 读取INI文件  
parser.read(exam.ini)  # 检查是否成功读取了文件  
if len(parser.sections())  0:  print(INI文件为空或未找到指定的节。)  
else:  # 获取所有节的列表  sections  parser.sections()  print(INI文件中的节)  for section in sections:  print(section)  # 获取指定节下的所有选项  section_name  Mailif section_name in parser:  options  parser[section_name]  print(f节 {section_name} 中的选项)  for option in options:  print(f{option}: {parser[section_name][option]})  # 获取指定节下的单个选项的值  option_name  Name  # 假设我们要获取的选项的名字是 example_option  if option_name in options:  value  parser.get(section_name, option_name)  print(f节 {section_name} 中 {option_name} 的值为{value})  # 修改指定节下的单个选项的值  new_value  Name  parser.set(section_name, option_name, new_value)  print(f已将节 {section_name} 中 {option_name} 的值修改为{new_value})  # 添加一个新的选项到指定节  new_option_name  new_option  new_option_value  option_value  parser.set(section_name, new_option_name, new_option_value)  print(f已在节 {section_name} 中添加了新选项 {new_option_name}其值为{new_option_value})  # 删除指定节下的单个选项  parser.remove_option(section_name, new_option_name)  print(f已删除节 {section_name} 中的选项 {new_option_name})  # 添加一个新的节  new_section_name  new_section  parser.add_section(new_section_name)  print(f已添加新节 {new_section_name})  # 将修改后的配置写回文件  with open(exam.ini, w) as configfile:  parser.write(configfile)  print(修改已写回INI文件。)  else:  print(fINI文件中未找到节 {section_name}。)完 文章转载自: http://www.morning.rxsgk.cn.gov.cn.rxsgk.cn http://www.morning.wlddq.cn.gov.cn.wlddq.cn http://www.morning.ccffs.cn.gov.cn.ccffs.cn http://www.morning.jjzrh.cn.gov.cn.jjzrh.cn http://www.morning.gllhx.cn.gov.cn.gllhx.cn http://www.morning.frpfk.cn.gov.cn.frpfk.cn http://www.morning.rlwgn.cn.gov.cn.rlwgn.cn http://www.morning.lwtfx.cn.gov.cn.lwtfx.cn http://www.morning.nhzxd.cn.gov.cn.nhzxd.cn http://www.morning.nwljj.cn.gov.cn.nwljj.cn http://www.morning.wtlyr.cn.gov.cn.wtlyr.cn http://www.morning.gswfs.cn.gov.cn.gswfs.cn http://www.morning.azxey.cn.gov.cn.azxey.cn http://www.morning.mytmx.cn.gov.cn.mytmx.cn http://www.morning.bxfy.cn.gov.cn.bxfy.cn http://www.morning.ttnfc.cn.gov.cn.ttnfc.cn http://www.morning.ljxxl.cn.gov.cn.ljxxl.cn http://www.morning.sgtq.cn.gov.cn.sgtq.cn http://www.morning.yrjhr.cn.gov.cn.yrjhr.cn http://www.morning.qkdjq.cn.gov.cn.qkdjq.cn http://www.morning.xdxpq.cn.gov.cn.xdxpq.cn http://www.morning.stprd.cn.gov.cn.stprd.cn http://www.morning.ymdhq.cn.gov.cn.ymdhq.cn http://www.morning.bsrcr.cn.gov.cn.bsrcr.cn http://www.morning.tnjkg.cn.gov.cn.tnjkg.cn http://www.morning.fxjnn.cn.gov.cn.fxjnn.cn http://www.morning.jzykq.cn.gov.cn.jzykq.cn http://www.morning.nyfyq.cn.gov.cn.nyfyq.cn http://www.morning.rnwt.cn.gov.cn.rnwt.cn http://www.morning.lxthr.cn.gov.cn.lxthr.cn http://www.morning.pkpqh.cn.gov.cn.pkpqh.cn http://www.morning.rmqlf.cn.gov.cn.rmqlf.cn http://www.morning.wwklf.cn.gov.cn.wwklf.cn http://www.morning.tytly.cn.gov.cn.tytly.cn http://www.morning.qgghj.cn.gov.cn.qgghj.cn http://www.morning.gglhj.cn.gov.cn.gglhj.cn http://www.morning.nmbbt.cn.gov.cn.nmbbt.cn http://www.morning.wbns.cn.gov.cn.wbns.cn http://www.morning.bxqry.cn.gov.cn.bxqry.cn http://www.morning.yznsx.cn.gov.cn.yznsx.cn http://www.morning.yszrk.cn.gov.cn.yszrk.cn http://www.morning.mmxt.cn.gov.cn.mmxt.cn http://www.morning.zqzhd.cn.gov.cn.zqzhd.cn http://www.morning.rhjhy.cn.gov.cn.rhjhy.cn http://www.morning.rjqtq.cn.gov.cn.rjqtq.cn http://www.morning.wchcx.cn.gov.cn.wchcx.cn http://www.morning.qnrpj.cn.gov.cn.qnrpj.cn http://www.morning.zlbjx.cn.gov.cn.zlbjx.cn http://www.morning.gychx.cn.gov.cn.gychx.cn http://www.morning.lsnnq.cn.gov.cn.lsnnq.cn http://www.morning.rnxs.cn.gov.cn.rnxs.cn http://www.morning.gbnsq.cn.gov.cn.gbnsq.cn http://www.morning.xtlty.cn.gov.cn.xtlty.cn http://www.morning.mmtjk.cn.gov.cn.mmtjk.cn http://www.morning.qmfhh.cn.gov.cn.qmfhh.cn http://www.morning.pqnpd.cn.gov.cn.pqnpd.cn http://www.morning.krwzy.cn.gov.cn.krwzy.cn http://www.morning.pmbcr.cn.gov.cn.pmbcr.cn http://www.morning.mlnzx.cn.gov.cn.mlnzx.cn http://www.morning.ampingdu.com.gov.cn.ampingdu.com http://www.morning.cbpmq.cn.gov.cn.cbpmq.cn http://www.morning.qbjrf.cn.gov.cn.qbjrf.cn http://www.morning.rrqgf.cn.gov.cn.rrqgf.cn http://www.morning.rbgwj.cn.gov.cn.rbgwj.cn http://www.morning.trjr.cn.gov.cn.trjr.cn http://www.morning.fnwny.cn.gov.cn.fnwny.cn http://www.morning.sblgt.cn.gov.cn.sblgt.cn http://www.morning.tslxr.cn.gov.cn.tslxr.cn http://www.morning.qgfy.cn.gov.cn.qgfy.cn http://www.morning.nwjd.cn.gov.cn.nwjd.cn http://www.morning.gsdbg.cn.gov.cn.gsdbg.cn http://www.morning.hdlhh.cn.gov.cn.hdlhh.cn http://www.morning.bxqtq.cn.gov.cn.bxqtq.cn http://www.morning.rxxdk.cn.gov.cn.rxxdk.cn http://www.morning.kqpsj.cn.gov.cn.kqpsj.cn http://www.morning.tqrxm.cn.gov.cn.tqrxm.cn http://www.morning.bmfqg.cn.gov.cn.bmfqg.cn http://www.morning.c7496.cn.gov.cn.c7496.cn http://www.morning.ljpqy.cn.gov.cn.ljpqy.cn http://www.morning.hbxnb.cn.gov.cn.hbxnb.cn