python_ConfigParser

本文详细介绍了Python中的ConfigParser模块,包括RawConfigParser、ConfigParser和SafeConfigParser三个对象的使用方法,以及它们各自的方法和属性,如add_section、get、set等,并提供了实例演示。

Python ConfigParser(python3中是configparser

包含3个object

RawConfigParser Objects

有如下方法:

RawConfigParser.defaults() 

RawConfigParser.add_section(section)  

Add a section named section to the instance

RawConfigParser.sections()  

Return a list of the sections available

RawConfigParser.remove_section(section)  

Remove the specified section from the configuration

Example:

>>> import ConfigParser

>>> config=ConfigParser.RawConfigParser()

>>> config.defaults()

{}

>>> config.add_section('section1')

>>> config.add_section('section2')

>>> config.sections()

['section2', 'section1']

>>> config.remove_section('section2')

True

>>> config.sections()

['section1']

RawConfigParser.set(section, option, value) 

If the given section exists, set the given option to the specified value 

RawConfigParser.get(section, option)  

Get an option value for the named section.

RawConfigParser.getint(section, option)  

A convenience method which coerces the option in the specified section to an integer.

RawConfigParser.getfloat(section, option)  

A convenience method which coerces the option in the specified section to a floating point number.

RawConfigParser.getboolean(section, option) 

the accepted values for the option are "1", "yes", "true", and "on", which cause this method to return True, and "0", "no", "false", and "off", which cause it to return False.

RawConfigParser.items(section)  

Return a list of (name, value) pairs for each option in the given section

RawConfigParser.remove_option(section, option) 

Remove the specified option from the specified section

RawConfigParser.write(fileobject) 

Write a representation of the configuration to the specified file object

RawConfigParser.read(filenames)

Read and parse a list of filenames, returning a list of filenames which were successfully parsed.

Example

>>> config.set('section1','a_int','1')

>>> config.set('section1','a_float','1.1')

>>> config.set('section1','a_bool','true')

>>> config.set('section1','name','kyle')

>>> config.getint('section1','a_int')

1

>>> config.getfloat('section1','a_float')

1.1000000000000001

>>> config.getboolean('section1','a_bool')

True

>>>

>>> config.get('section1','name')

'kyle'

>>> f=open('text.txt','wb')

>>> config.write(f)

>>> f.close()

>>> config.read('text.txt')

['text.txt']

>>> for item in config.items('section1'):

...     print item

... 

('a_int', '1')

('a_bool', 'true')

('name', 'kyle')

('a_float', '1.1')

>>> config.remove_option('section1','a_int')

True

>>> for item in config.items('section1'):

...     print item

... 

('a_bool', 'true')

('a_float', '1.1')

('name', 'kyle')

 

ConfigParser Objects(extends some methods of the RawConfigParser interface):

ConfigParser.get(section, option[, raw[, vars]])

使用方法基本与RawConfigParser.get(section, option)相同,区别如下:

>>> config=ConfigParser.ConfigParser()

>>> config.read('text.txt')

['text.txt']

>>> config.set('section1','tt','%(a_int)s is not equal %(a_float)s')

>>> config.get('section1','tt',1)

'%(a_int)s is not equal %(a_float)s'  

>>> config.get('section1','tt',0)

'1 is not equal 1.1'

ConfigParser.items(section[, raw[, vars]])

RawConfigParser.items(section)中的区别 和get方法一样

SafeConfigParser Objectsimplements the same extended interface as ConfigParser):

SafeConfigParser.set(section, option, value)

Example:

>>> config=ConfigParser.SafeConfigParser({'a_int':'3'})

>>> config.read('text.txt')

['text.txt']

>>> print config.get('section1','a_int')

1

>>> config.remove_option('section1','a_int')

True

>>> print config.get('section1','a_int')

3

>>> 

参考:http://docs.python.org/2/library/configparser.html

Python 中的 `configparser` 模块是标准的一部分,用于处理配置文件。配置文件通常用于存储应用程序的配置信息,例如数据连接参数、日志级别设置等。该模块支持读取、写入和修改配置文件,这些文件通常采用类似 INI 格式的结构。这种格式与 Windows 的 INI 文件格式相同,因此 `configparser` 可以轻松地与这些文件进行交互 [^1]。 ### 基本用法 #### 对象初始化 使用 `configparser` 时,首先需要创建一个 `ConfigParser` 对象: ```python import configparser config = configparser.ConfigParser() ``` #### 配置文件格式 一个典型的 INI 文件由多个节(section)组成,每个节包含多个键值对(option 和 value): ``` [DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 [bitbucket.org] User = hg [topsecret.server.com] Port = 22 ForwardX11 = no ``` #### 读取配置文件 使用 `read()` 方法可以加载配置文件: ```python config.read('example.ini') ``` #### 获取所有的 sections 可以获取配置文件中的所有节: ```python sections = config.sections() ``` #### 获取指定 section 下的 option 值 使用 `get()` 方法可以获取指定节下的选项值: ```python server_alive_interval = config.get('DEFAULT', 'ServerAliveInterval') ``` #### 获取指定 section 的所有配置信息 可以使用 `items()` 方法来获取指定节的所有配置信息: ```python items = config.items('bitbucket.org') ``` #### 修改某个 option 的值 使用 `set()` 方法可以修改某个选项的值,并使用 `write()` 方法将更改写入文件: ```python config.set('DEFAULT', 'CompressionLevel', '10') with open('example.ini', 'w') as configfile: config.write(configfile) ``` #### 添加 section 和 option 使用 `add_section()` 方法可以添加新的节: ```python config.add_section('new_section') ``` #### 删除 section 和 option 使用 `remove_section()` 或 `remove_option()` 方法可以删除节或选项: ```python config.remove_section('topsecret.server.com') config.remove_option('DEFAULT', 'CompressionLevel') ``` #### 异常处理 在使用 `configparser` 模块时,可能会遇到一些异常,例如试图访问不存在的节或选项时会引发 `NoSectionError` 或 `NoOptionError`。 ### 常见用途 `configparser` 模块常用于应用程序中以管理配置数据,这使得配置信息易于维护并且可以避免硬编码配置信息。此外,它也支持将配置数据转换为字典形式以便进一步处理 [^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值