欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-04-05 16:53:40
简介想写一个登录注册的demo,但是以前的demo数据都写在程序里面,每一关掉程序数据就没保存住。。于是想着写到配置文件里好了python自身提供了一个module - configparser,来进...

简介

想写一个登录注册的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利用configparser对配置文件进行读写操作的文章就介绍到这了,更多相关python configparser配置文件读写内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!