python configparser_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方法

初始化

importconfigparser

importos

# 生成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=)

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)

getboolean

getfloat同get,返回值为float

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

>>> thread

20.0

>>> type(thread)

getint 同get,返回值为int

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

>>> thread

20

>>> type(thread)

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=, 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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值