Introducción
Quiero escribir una demostración para iniciar sesión y registrarme, pero los datos de la demostración anterior están escritos en el programa y los datos no se guardan cada vez que se cierra el programa. .
Así que pensé en escribir en el archivo de configuración.
Python mismo proporciona un módulo-configparser para leer y escribir archivos de configuración.
Analizador de archivos de configuración.
Un archivo de configuración consta de secciones, encabezadas por un encabezado "[sección]"
y seguidas por entradas "nombre: valor", con continuaciones y similares en
el estilo de RFC 822.
Nota El módulo ConfigParser ha sido renombrado a configparser en Python 3. La herramienta 2to3 adaptará automáticamente las importaciones al convertir sus fuentes a Python 3.
En py2, el módulo se llama ConfigParser, y en py3, las letras están todas en minúsculas. Este artículo toma py3 como ejemplo
clase
Propiedades y métodos de 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.
Formato de datos del archivo de configuración
El siguiente config.ini muestra el formato de datos del archivo de configuración, encerrado entre corchetes [] es una sección como Default y Color; cada sección tiene múltiples opciones, como serveraliveinterval, compresión, etc.
La opción es donde guardamos nuestros propios datos, similar al par clave-valor optionname = value u optionname: value (también se puede configurar para permitir valores nulos)
[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
tipo de datos
En los datos guardados por py configparser, el valor del valor se guarda como un tipo de cadena y debe convertirlo al tipo de datos que necesita.
Los analizadores de configuración no adivinan los tipos de datos de los valores en los archivos de configuración, siempre los almacenan internamente como cadenas. Esto significa que si necesita otros tipos de datos, debe convertir por su cuenta:
P.ej
>>> int(topsecret['Port'])
50022
>>> float(topsecret['CompressionLevel'])
9.0
Método de uso común
Abra el archivo de configuración
import configparser
file = 'config.ini'
# 创建配置文件对象
cfg = configparser.ConfigParser(comment_prefixes='#')
# 读取配置文件
cfg.read(file, encoding='utf-8')
Solo abra aquí y no haga nada para leer y cambiar
Leer todas las secciones del archivo de configuración
Reemplace el archivo con el archivo de configuración correspondiente
import configparser
file = 'config.ini'
cfg = configparser.ConfigParser(comment_prefixes='#')
cfg.read(file, encoding='utf-8')
# 获取所有section
sections = cfg.sections()
# 显示读取的section结果
print(sections)
¡¡¡Determina si hay una sección correspondiente !!!
El programa terminará de manera anormal cuando no haya una sección correspondiente para operar directamente
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")
Determine la opción correspondiente en la sección
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")
Agregar sección y opción
Lo más importante: ¡Finalmente, asegúrese de escribir un archivo para guardar! ! ! De lo contrario, el resultado de la modificación del programa no se modificará en el archivo.
- Antes de agregar una sección, verifique si existe, de lo contrario, si hay un nombre duplicado, se informará un error y el programa finalizará de manera anormal
- Asegúrese de que la sección exista antes de agregar la opción; de lo contrario, es igual a 1.
La opción se creará si la opción no existe cuando se modifica la opción
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)
Opción de eliminar
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)
Eliminar sección
Al eliminar una sección, todas las opciones debajo de la sección se eliminarán automáticamente de forma recursiva, úsela con precaución
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)
Ejemplo
Crea un archivo de configuración
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 : [email protected]
@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', '[email protected]')
cfg.set('User', 'Tony', '[email protected]')
# 把所作的修改写入配置文件,并不是完全覆盖文件
with open(file, 'w', encoding='utf-8') as configfile:
cfg.write(configfile)
La ejecución del programa anterior creará un archivo de configuración config.ini y luego agregará la sección y
el contenido del archivo de valor de opción como se muestra a continuación
[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 = [email protected]
tony = [email protected]
Referencias
- Analizador de archivos de configuración - py2
- Analizador de archivos de configuración - py3
- Python lee archivos de configuración (ini, yaml, xml) -ini es de solo lectura y no está escrito. .
- La apertura del archivo de configuración de escritura de Python no está estandarizada, los comentarios entran en conflicto con la referencia anterior