详解Python利用configparser对配置文件进行读写操作
作者:Kearney form An idea 发布时间:2022-08-02 22:24:38
简介
想写一个登录注册的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
Configuration file parser - py2
Configuration file parser - py3
python读取配置文件(ini、yaml、xml)-ini只读不写。。
python 编写配置文件 - open不规范,注释和上一篇参考冲突
来源:https://blog.csdn.net/weixin_43031092/article/details/109174379
猜你喜欢
- Firefox 的 Jetpack 可以让我们很轻松地创建 Firefox 插件,仅通过已掌握的前端技能(HTML/CSS/JS),估计让人
- 最近的项目中大量涉及数据的预处理工作,对于ndarray的使用非常频繁。其中ndarray如何进行数值筛选,总结了几种方法。1.按某些固定值
- RabbitMQ可以当做一个消息代理,它的核心原理非常简单:即接收和发送消息,可以把它想象成一个邮局:我们把信件放入邮箱,邮递员就会把信件投
- 在使用pytorch的时候,经常会涉及到两种数据格式tensor和ndarray之间的转换,这里总结一下两种格式的转换:1. tensor
- 在Mysql中很多表都包含可为NULL(空值)的列,即使应用程序并不需要保存NULL也是如此,这是因为可为NULL是列的默认属性。但我们常在
- 前言:作为一个.NET开发者而已,有着宇宙最强IDE:Visual Studio加持,让我们的开发效率得到了更好的提升。我们不需要担心环境变
- 记录下Django关于日期的配置,以及如何根据日期滚动切割日志的问题。配置的源码在githun上 https://github.com/bl
- 问题描述:ImportError: No module named ‘XXXX'解决方式一: 将XXXX包放在python的site
- 一.ajax介绍1、ajax的含义Ajax全称“Async Javascript And XML”即:异步的javascript和XML。它
- 二进制日志二进制日志中以“事件”的形式记录了数据库中数据的变化情况,对于MySQL数据库的灾难恢复起
- 1. 需求概述最近接到一份PDF资料需要打印,奈何页面是如图所示的A3格式的,奈何目前条件只支持打印A4。我想要把每页的一个大页面裁成两个小
- 了解了上一篇的ADO.NET简介,我们就可以来对数据库进行增删改查等基本操作了!下面是每种操作的具体实现。先在自定义类的头部定义好数据库连接
- 每次说到javascript的面向对象,总感觉自己心里懂,但是却不知道该怎么说,这就是似懂非懂到表现,于是乎,每次一说,就要到处去查找资料,
- 前言最近,老板让写一个程序把yolov5检测模型部署到web端,在网页直接进行目标检测。经过1个星期的努力,终于实现基本功能??(累晕了)。
- 这篇论坛文章(赛迪网技术社区)着重介绍了有关SQL注入防御的防御策略及实施步骤,详细内容请参考下文:从去年下半年开始,很多网站被损害,他们在
- 今天给大家分享一个简单的python脚本,使用python进行http的接口测试,脚本很简单,逻辑是:读取excel写好的测试用例,然后根据
- 前言作为一个数据库,作为数据库中的一张表,随着用户的增多随着时间的推移,总有一天,数据量会大到一个难以处理的地步。这时仅仅一张表的数据就已经
- SQL Server 阻止了对组件 'Ad Hoc Distributed&nbs
- 在网上搜索了半天,最简单的办法是在新的数据库中创建和原名字一样的数据库,然后把.frm 文件拷贝进去就OK了。 可是,有些时候这样不行,查询
- 简单的 TodoList实现一个简单的 todolist,当我输入内容后,点击提交自动添加在下面,如下图所示:用代码实现这个效果:<d