search
HomeBackend DevelopmentPython TutorialPython中使用ConfigParser解析ini配置文件实例

ini文件是windows中经常使用的配置文件,主要的格式为:

复制代码 代码如下:

[Section1]
option1 : value1
option2 : value2

python提供了一个简单的模块ConfigParser可以用来解析类似这种形式的文件。对于ConfigParser模块可以解析key:value和key=value这样的类型,对于#和;开头的行将会自动忽视掉。相当于注释行。常用的函数:
复制代码 代码如下:

ConfigParser.RawConfigParser()

RawConfigParser Object的操作有:

.sections() : 返回所有可用的section
.addsection(sectionname) :添加section
.set(sectionname, optionname, optionvalue): 添加option
.hassection(sectionname) :判断
.options(sectionname) : 返回section下可用的option
.hasoption(sectionname, optionname) : 判断
.read(filename) : 读取文件
.wrie(filename) : 将RawConfigParser对象写到文件中
.get(sectionname, optionname) : 获取值, 默认的是返回string类型
.getfloat, .getint, .getboolean : 获取不同类型的返回值,参数和get的参数一样
.items(sectionname) :列出section下的所有key:value
.remove(sectionname) :删除section
.remove(sectionname, option_name) : 删除section下的某个option


Demo -- 生成文件
复制代码 代码如下:

$ cat ini_demo.py
# -*- coding:utf-8 -*-

import ConfigParser

def gen_ini():
    ftest = open('test','w')
    config_write = ConfigParser.RawConfigParser()
    config_write.add_section('Section_a')
    config_write.add_section('Section_b')
    config_write.add_section('Section_c')
    config_write.set('Section_a','option_a1','apple_a1')
    config_write.set('Section_a','option_a2','banana_a2')
    config_write.set('Section_b','option_b1','apple_b1')
    config_write.set('Section_b','option_b2','banana_b2')
    config_write.set('Section_c','option_c1','apple_c1')
    config_write.set('Section_c','option_c2','banana_c2')  
    config_write.write(ftest)
    ftest.close()

if __name__ == "__main__":
    gen_ini()


最后生成的文件为:
复制代码 代码如下:

$ cat test
[Section_a]
option_a1 = apple_a1
option_a2 = banana_a2

[Section_c]
option_c2 = banana_c2
option_c1 = apple_c1

[Section_b]
option_b1 = apple_b1
option_b2 = banana_b2
Demo -- 读取文件

def read_ini():
    config_read = ConfigParser.RawConfigParser()
    config_read.read('test')
    print config_read.sections()
    print config_read.items('Section_a')
    print config_read.get('Section_a','option_a1')


最后的结果为:
复制代码 代码如下:

['Section_a', 'Section_c', 'Section_b']
[('option_a2', 'banana_a2'), ('option_a1', 'apple_a1')]
apple_a1
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you append elements to a Python array?How do you append elements to a Python array?Apr 30, 2025 am 12:19 AM

InPython,youappendelementstoalistusingtheappend()method.1)Useappend()forsingleelements:my_list.append(4).2)Useextend()or =formultipleelements:my_list.extend(another_list)ormy_list =[4,5,6].3)Useinsert()forspecificpositions:my_list.insert(1,5).Beaware

How do you debug shebang-related issues?How do you debug shebang-related issues?Apr 30, 2025 am 12:17 AM

The methods to debug the shebang problem include: 1. Check the shebang line to make sure it is the first line of the script and there are no prefixed spaces; 2. Verify whether the interpreter path is correct; 3. Call the interpreter directly to run the script to isolate the shebang problem; 4. Use strace or trusts to track the system calls; 5. Check the impact of environment variables on shebang.

How do you remove elements from a Python array?How do you remove elements from a Python array?Apr 30, 2025 am 12:16 AM

Pythonlistscanbemanipulatedusingseveralmethodstoremoveelements:1)Theremove()methodremovesthefirstoccurrenceofaspecifiedvalue.2)Thepop()methodremovesandreturnsanelementatagivenindex.3)Thedelstatementcanremoveanitemorslicebyindex.4)Listcomprehensionscr

What data types can be stored in a Python list?What data types can be stored in a Python list?Apr 30, 2025 am 12:07 AM

Pythonlistscanstoreanydatatype,includingintegers,strings,floats,booleans,otherlists,anddictionaries.Thisversatilityallowsformixed-typelists,whichcanbemanagedeffectivelyusingtypechecks,typehints,andspecializedlibrarieslikenumpyforperformance.Documenti

What are some common operations that can be performed on Python lists?What are some common operations that can be performed on Python lists?Apr 30, 2025 am 12:01 AM

Pythonlistssupportnumerousoperations:1)Addingelementswithappend(),extend(),andinsert().2)Removingitemsusingremove(),pop(),andclear().3)Accessingandmodifyingwithindexingandslicing.4)Searchingandsortingwithindex(),sort(),andreverse().5)Advancedoperatio

How do you create multi-dimensional arrays using NumPy?How do you create multi-dimensional arrays using NumPy?Apr 29, 2025 am 12:27 AM

Create multi-dimensional arrays with NumPy can be achieved through the following steps: 1) Use the numpy.array() function to create an array, such as np.array([[1,2,3],[4,5,6]]) to create a 2D array; 2) Use np.zeros(), np.ones(), np.random.random() and other functions to create an array filled with specific values; 3) Understand the shape and size properties of the array to ensure that the length of the sub-array is consistent and avoid errors; 4) Use the np.reshape() function to change the shape of the array; 5) Pay attention to memory usage to ensure that the code is clear and efficient.

Explain the concept of 'broadcasting' in NumPy arrays.Explain the concept of 'broadcasting' in NumPy arrays.Apr 29, 2025 am 12:23 AM

BroadcastinginNumPyisamethodtoperformoperationsonarraysofdifferentshapesbyautomaticallyaligningthem.Itsimplifiescode,enhancesreadability,andboostsperformance.Here'showitworks:1)Smallerarraysarepaddedwithonestomatchdimensions.2)Compatibledimensionsare

Explain how to choose between lists, array.array, and NumPy arrays for data storage.Explain how to choose between lists, array.array, and NumPy arrays for data storage.Apr 29, 2025 am 12:20 AM

ForPythondatastorage,chooselistsforflexibilitywithmixeddatatypes,array.arrayformemory-efficienthomogeneousnumericaldata,andNumPyarraysforadvancednumericalcomputing.Listsareversatilebutlessefficientforlargenumericaldatasets;array.arrayoffersamiddlegro

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools