python configparser模块

configparser介绍

configparser模块主要用于读取配置文件,导入方法:import configparser

ini配置文件语法

ini文件格式是某些平台或软件上的配置文件的非正式标准,以节(section)和键(key)构成

格式如下:

 

[section_1]

name_1 = value_1

name_2 = value_2

 

实验配置文件./config/config.ini如下:

configparser.ConfigParser方法

初始化

import configparser
import os

# 生成ConfigParser对象
config = configparser.ConfigParser()
# 读取配置文件
currentdir = os.path.dirname(os.path.realpath(__file__))
confdir = os.path.join(currentdir, "config")
cfgfile = os.path.join(confdir, "config.ini")
config.read(cfgfile, encoding='utf-8')

BOOLEAN_STATES

NONSPACECRE

OPTCRE

OPTCRE_NV

SECTCRE

add_section

clear

converters

defaults

get获取指定section中指定键对应的值

语法

>>> help (configparser.ConfigParser.get)

Help on function get in module configparser:

 

get(self, section, option, *, raw=False, vars=None, fallback=<object object at 0x0000018464F4C1A0>)

Get an option value for a given section.

 

If `vars' is provided, it must be a dictionary. The option is looked up

in `vars' (if provided), `section', and in `DEFAULTSECT' in that order.

If the key is not found and `fallback' is provided, it is used as

a fallback value. `None' can be provided as a `fallback' value.

 

If interpolation is enabled and the optional argument `raw' is False,

all interpolations are expanded in the return values.

 

Arguments `raw', `vars', and `fallback' are keyword only.

 

The section DEFAULT is special.

示例

>>> config.get('3PAR','hostfile')

'3par.txt'

>>> config.get('3PAR1','other',fallback = 'no')

'no'

>>> config.get('3PAR','other',fallback = 'no') #不存在的section或键会报错,可以指定默认值

'no'

>>> config.get('3PAR','other',fallback = None)

>>>

>>> config.get('3PAR','threading') #返回值为字符串

'20'

>>> thread = config.get('3PAR','threading')

>>> type(thread)

<class 'str'>

getboolean

getfloat同get,返回值为float

>>> thread = config.getfloat('3PAR','threading')

>>> thread

20.0

>>> type(thread)

<class 'float'>

getint 同get,返回值为int

>>> thread = config.getint('3PAR','threading')

>>> thread

20

>>> type(thread)

<class 'int'>

has_option检查option是否存在

语法

>> help (configparser.ConfigParser.has_option)

Help on function has_option in module configparser:

 

has_option(self, section, option)

Check for the existence of a given option in a given section.

If the specified `section' is None or an empty string, DEFAULT is

assumed. If the specified `section' does not exist, returns False.

 

示例

>>> config.has_option('3PAR','hostfile')

True

>>> config.has_option('3PAR','hostfile1')

False

>>> config.has_option('3PAR1','hostfile')

False

has_section 检查section是否存在

语法

>>> help (configparser.ConfigParser.has_section)

Help on function has_section in module configparser:

 

has_section(self, section)

Indicate whether the named section is present in the configuration.

 

The DEFAULT section is not acknowledged.

示例

>>> config.has_section('3PAR')

True

>>> config.has_section('3PA')

False

items返回指定section中键值对组成的列表

语法

>>> help (configparser.ConfigParser.items)

Help on function items in module configparser:

 

items(self, section=<object object at 0x0000018464F4C1A0>, raw=False, vars=None)

Return a list of (name, value) tuples for each option in a section.

 

All % interpolations are expanded in the return values, based on the

defaults passed into the constructor, unless the optional argument

`raw' is true. Additional substitutions may be provided using the

`vars' argument, which must be a dictionary whose contents overrides

any pre-existing defaults.

 

The section DEFAULT is special.

示例

>>> config.items('3PAR')

[('hostfile', '3par.txt'), ('threading', '20')]

keys

options返回指定section的键组成的列表

语法

>>> help (configparser.ConfigParser.options)

Help on function options in module configparser:

 

options(self, section)

Return a list of option names for the given section name.

示例

>>> config.options('3PAR')

['hostfile', 'threading']

optionxform

pop

popitem

read读取配置文件,返回可读取的配置文件列表

语法

>>> help (configparser.ConfigParser.read)

Help on function read in module configparser:

 

read(self, filenames, encoding=None)

Read and parse a filename or a list of filenames.

 

Files that cannot be opened are silently ignored; this is

designed so that you can specify a list of potential

configuration file locations (e.g. current directory, user's

home directory, systemwide directory), and all existing

configuration files in the list will be read. A single

filename may also be given.

 

Return list of successfully read files.

示例

>>> config = configparser.ConfigParser()

>>> config.read(r'C:\Users\h15154\Desktop\runcmdv2\config\config.ini', encoding='utf-8')

['C:\\Users\\h15154\\Desktop\\runcmdv2\\config\\config.ini']

read_dict

read_file读取类文件对象

语法

>>> help (configparser.ConfigParser.read_file)

Help on function read_file in module configparser:

 

read_file(self, f, source=None)

Like read() but the argument must be a file-like object.

 

The `f' argument must be iterable, returning one line at a time.

Optional second argument is the `source' specifying the name of the

file being read. If not given, it is taken from f.name. If `f' has no

`name' attribute, `<???>' is used.

read_string

readfp

remove_option

remove_section

sections 返回section列表

语法

>>> help (configparser.ConfigParser.sections)

Help on function sections in module configparser:

 

sections(self)

Return a list of section names, excluding [DEFAULT]

 

示例

>>> config.sections()

['3PAR', 'SAN']

set

setdefault

update

values

write

posted @ 2020-10-02 21:45  jeancheng  阅读(879)  评论(0编辑  收藏  举报