详解Python利用configparser对配置文件进行读写操作


Posted in Python onNovember 03, 2020

简介

想写一个登录注册的demo,但是以前的demo数据都写在程序里面,每一关掉程序数据就没保存住。。
于是想着写到配置文件里好了
Python自身提供了一个Module - configparser,来进行对配置文件的读写

Configuration file parser.
A configuration file consists of sections, lead by a “[section]” header,
and followed by “name: value” entries, with continuations and such in
the style of RFC 822.

Note The ConfigParser module has been renamed to configparser in Python 3. The 2to3 tool will automatically adapt imports when converting your sources to Python 3.

在py2中,该模块叫ConfigParser,在py3中把字母全变成了小写。本文以py3为例

ConfigParser的属性和方法

ConfigParser -- responsible for parsing a list of
   configuration files, and managing the parsed database.
 
 methods:
 
 __init__(defaults=None, dict_type=_default_dict, allow_no_value=False,
  delimiters=('=', ':'), comment_prefixes=('#', ';'),
  inline_comment_prefixes=None, strict=True,
  empty_lines_in_values=True, default_section='DEFAULT',
  interpolation=<unset>, converters=<unset>):
 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 won't 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 don't do
 any sort of interpolation, whereas ConfigParser uses an instance of
 BasicInterpolation. The library also provides a ``zc.buildbot``
 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, encoding=None)
 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, filename=None)
 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, raw=False, vars=None, 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, raw=False, vars=None, fallback=_UNSET)
 Like get(), but convert value to an integer.
 
 getfloat(section, options, raw=False, vars=None, fallback=_UNSET)
 Like get(), but convert value to a float.
 
 getboolean(section, options, raw=False, vars=None, 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, raw=False, vars=None)
 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_delimiters=True)
 Write the configuration state in .ini format. If
 `space_around_delimiters' is True (the default), delimiters
 between keys and values are surrounded by spaces.

配置文件的数据格式

下面的config.ini展示了配置文件的数据格式,用中括号[]括起来的为一个section例如Default、Color;每一个section有多个option,例如serveraliveinterval、compression等。
option就是我们用来保存自己数据的地方,类似于键值对 optionname = value 或者是optionname : value (也可以设置允许空值)

[Default]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes
values like this: 1000000
or this: 3.14159265359
[No Values]
key_without_value
empty string value here =

[Color]
isset = true
version = 1.1.0
orange = 150,100,100
lightgreen = 0,220,0

数据类型

在py configparser保存的数据中,value的值都保存为字符串类型,需要自己转换为自己需要的数据类型

Config parsers do not guess datatypes of values in configuration files, always storing them internally as strings. This means that if you need other datatypes, you should convert on your own:

例如

>>> int(topsecret['Port'])
50022
>>> float(topsecret['CompressionLevel'])
9.0

常用方法method

打开配置文件

import configparser

file = 'config.ini'

# 创建配置文件对象
cfg = configparser.ConfigParser(comment_prefixes='#')
# 读取配置文件
cfg.read(file, encoding='utf-8')

这里只打开不做什么读取和改变

读取配置文件的所有section

file处替换为对应的配置文件即可

import configparser

file = 'config.ini'
cfg = configparser.ConfigParser(comment_prefixes='#')
cfg.read(file, encoding='utf-8')

# 获取所有section
sections = cfg.sections()
# 显示读取的section结果
print(sections)

判断有没有对应的section!!!

当没有对应的section就直接操作时程序会非正常结束

import configparser

file = 'config.ini'
cfg = configparser.ConfigParser(comment_prefixes='#')
cfg.read(file, encoding='utf-8')
if cfg.has_section("Default"): # 有没有"Default" section
 print("存在Defaul section")
else:
	print("不存在Defaul section")

判断section下对应的Option

import configparser

file = 'config.ini'
cfg = configparser.ConfigParser(comment_prefixes='#')
cfg.read(file, encoding='utf-8')
# 检测Default section下有没有"CompressionLevel" option
if cfg.cfg.has_option('Default', 'CompressionLevel'): 
 print("存在CompressionLevel option")
else:
	print("不存在CompressionLevel option")

添加section和option

最最重要的事情: 最后一定要写入文件保存!!!不然程序修改的结果不会修改到文件里

  • 添加section前要检测是否存在,否则存在重名的话就会报错程序非正常结束
  • 添加option前要确定section存在,否则同1

option在修改时不存在该option就会创建该option

import configparser

file = 'config.ini'
cfg = configparser.ConfigParser(comment_prefixes='#')
cfg.read(file, encoding='utf-8')

if not cfg.has_section("Color"): # 不存在Color section就创建
 cfg.add_section('Color')

# 设置sectin下的option的value,如果section不存在就会报错
cfg.set('Color', 'isset', 'true')
cfg.set('Color', 'version', '1.1.0') 
cfg.set('Color', 'orange', '150,100,100')

# 把所作的修改写入配置文件
with open(file, 'w', encoding='utf-8') as configfile:
 cfg.write(configfile)

删除option

import configparser

file = 'config.ini'
cfg = configparser.ConfigParser(comment_prefixes='#')
cfg.read(file, encoding='utf-8')

cfg.remove_option('Default', 'CompressionLevel'

# 把所作的修改写入配置文件
with open(file, 'w', encoding='utf-8') as configfile:
 cfg.write(configfile)

删除section

删除section的时候会递归自动删除该section下面的所有option,慎重使用

import configparser

file = 'config.ini'
cfg = configparser.ConfigParser(comment_prefixes='#')
cfg.read(file, encoding='utf-8')

cfg.remove_section('Default')

# 把所作的修改写入配置文件
with open(file, 'w', encoding='utf-8') as configfile:
 cfg.write(configfile)

实例

创建一个配置文件

import configparser

file = 'config.ini'

# 创建配置文件对象
cfg = configparser.ConfigParser(comment_prefixes='#')
# 读取配置文件
cfg.read(file, encoding='utf-8')```

# 实例
## 创建一个配置文件
下面的demo介绍了如何检测添加section和设置value
```python
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : file.py
@Desc : 使用configparser读写配置文件demo
@Author : Kearney
@Contact : 191615342@qq.com
@Version : 0.0.0
@License : GPL-3.0
@Time : 2020/10/20 10:23:52
'''
import configparser

file = 'config.ini'

# 创建配置文件对象
cfg = configparser.ConfigParser(comment_prefixes='#')
# 读取配置文件
cfg.read(file, encoding='utf-8')

if not cfg.has_section("Default"): # 有没有"Default" section
 cfg.add_section("Default") # 没有就创建

# 设置"Default" section下的option的value
# 如果这个section不存在就会报错,所以上面要检测和创建
cfg.set('Default', 'ServerAliveInterval', '45')
cfg.set('Default', 'Compression', 'yes')
cfg.set('Default', 'CompressionLevel', '9')
cfg.set('Default', 'ForwardX11', 'yes')

if not cfg.has_section("Color"): # 不存在Color就创建
 cfg.add_section('Color')

# 设置sectin下的option的value,如果section不存在就会报错
cfg.set('Color', 'isset', 'true')
cfg.set('Color', 'version', '1.1.0') 
cfg.set('Color', 'orange', '150,100,100')
cfg.set('Color', 'lightgreen', '0,220,0')

if not cfg.has_section("User"): 
 cfg.add_section('User')

cfg.set('User', 'iscrypted', 'false')
cfg.set('User', 'Kearney', '191615342@qq.com')
cfg.set('User', 'Tony', 'backmountain@gmail.com')

# 把所作的修改写入配置文件,并不是完全覆盖文件
with open(file, 'w', encoding='utf-8') as configfile:
 cfg.write(configfile)

跑上面的程序就会创建一个config.ini的配置文件,然后添加section和option-value
文件内容如下所示

[Default]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes

[Color]
isset = true
version = 1.1.0
orange = 150,100,100
lightgreen = 0,220,0

[User]
iscrypted = false
kearney = 191615342@qq.com
tony = backmountain@gmail.com

References

到此这篇关于详解Python利用configparser对配置文件进行读写操作的文章就介绍到这了,更多相关Python configparser配置文件读写内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Python笔记(叁)继续学习
Oct 24 Python
wxPython窗口中文乱码解决方法
Oct 11 Python
介绍Python的Django框架中的QuerySets
Apr 20 Python
python进阶_浅谈面向对象进阶
Aug 17 Python
Python3中的列表生成式、生成器与迭代器实例详解
Jun 11 Python
用Python分析3天破10亿的《我不是药神》到底神在哪?
Jul 12 Python
python检测服务器端口代码实例
Aug 31 Python
Python关于反射的实例代码分享
Feb 20 Python
python使用pymongo与MongoDB基本交互操作示例
Apr 09 Python
使用Python FastAPI构建Web服务的实现
Jun 08 Python
Pycharm2020.1安装无法启动问题即设置中文插件的方法
Aug 07 Python
python获取天气接口给指定微信好友发天气预报
Dec 28 Python
Python抓包并解析json爬虫的完整实例代码
Nov 03 #Python
python中not、and和or的优先级与详细用法介绍
Nov 03 #Python
如何基于Python按行合并两个txt
Nov 03 #Python
Python txt文件如何转换成字典
Nov 03 #Python
Python headers请求头如何实现快速添加
Nov 03 #Python
python time()的实例用法
Nov 03 #Python
Python-openpyxl表格读取写入的案例详解
Nov 02 #Python
You might like
IIS6.0中配置php服务全过程解析
2013/08/07 PHP
PHP类的封装与继承详解
2015/09/29 PHP
php记录搜索引擎爬行记录的实现代码
2018/03/02 PHP
JS对象转换为Jquery对象示例
2014/01/26 Javascript
Javascript数组与字典用法分析
2014/12/13 Javascript
JavaScript中的值类型详细介绍
2014/12/29 Javascript
javascript 闭包详解
2015/02/15 Javascript
基于jQuery实现的向下滑动二级菜单效果代码
2015/08/31 Javascript
javascript中闭包(Closure)详解
2016/01/06 Javascript
自己动手制作基于jQuery的Web页面加载进度条插件
2016/06/03 Javascript
JS实现简单易用的手机端浮动窗口显示效果
2016/09/07 Javascript
针对后台列表table拖拽比较实用的jquery拖动排序
2016/10/10 Javascript
Vue开发过程中遇到的疑惑知识点总结
2017/01/20 Javascript
Vue2.0 UI框架ElementUI使用方法详解
2017/04/14 Javascript
JavaScript操作文件_动力节点Java学院整理
2017/06/30 Javascript
JavaScript阻止表单提交方法(附代码)
2017/08/15 Javascript
JS简单数组排序操作示例【sort方法】
2019/05/17 Javascript
Vue中的组件及路由使用实例代码详解
2019/05/22 Javascript
关于JS模块化的知识点分享
2019/10/16 Javascript
jQuery三组基本动画与自定义动画操作实例总结
2020/05/09 jQuery
Python中optionParser模块的使用方法实例教程
2014/08/29 Python
python中找出numpy array数组的最值及其索引方法
2018/04/17 Python
Python中存取文件的4种不同操作
2018/07/02 Python
Numpy之文件存取的示例代码
2018/08/03 Python
python通过zabbix api获取主机
2018/09/17 Python
Python 使用生成器代替线程的方法
2020/08/04 Python
CSS3实现伪类hover离开时平滑过渡效果示例
2017/08/10 HTML / CSS
Corelle官方网站:购买康宁餐具
2016/11/02 全球购物
Bibloo荷兰:女士、男士和儿童的服装、鞋子和配饰
2019/02/25 全球购物
群众路线党课主持词
2014/04/01 职场文书
中国梦口号
2014/06/13 职场文书
2015年幼儿园新年寄语
2014/12/08 职场文书
刑事撤诉申请书
2015/05/18 职场文书
让子弹飞观后感
2015/06/11 职场文书
创业计划书之川味火锅店
2019/09/02 职场文书
原型和原型链 prototype和proto的区别详情
2021/11/02 Javascript