python-configparser模塊


一、configparser介紹
configparser模塊主要用於讀取配置文件,導入方法:import configparser

二、基本操作

2.1、獲取節點sections
ConfigParserObject.sections()
以列表形式返回configparser對象的所有節點信息

2.2、獲取指定節點的的所有配置信息
ConfigParserObject.items(section)
以列表形式返回某個節點section對應的所有配置信息

2.3、獲取指定節點的options
ConfigParserObject.options(section)
以列表形式返回某個節點section的所有key值

2.4、獲取指定節點下指定option的值
ConfigParserObject.get(section, option)
返回結果是字符串類型
ConfigParserObject.getint(section, option)
返回結果是int類型
ConfigParserObject.getboolean(section, option)
返回結果是bool類型
ConfigParserObject.getfloat(section, option)
返回結果是float類型

2.5、檢查section或option是否存在
ConfigParserObject.has_section(section)
ConfigParserObject.has_option(section, option)
返回bool值,若存在返回True,不存在返回False

2.6、添加section
ConfigParserObject.add_section(section)
如果section不存在,則添加節點section;
若section已存在,再執行add操作會報錯configparser.DuplicateSectionError: Section XX already exists

2.7、修改或添加指定節點下指定option的值
ConfigParserObject.set(section, option, value)
若option存在,則會替換之前option的值為value;
若option不存在,則會創建optiion並賦值為value

2.8、刪除section或option
ConfigParserObject.remove_section(section)
若section存在,執行刪除操作;
若section不存在,則不會執行任何操作
ConfigParserObject.remove_option(section, option)
若option存在,執行刪除操作;
若option不存在,則不會執行任何操作;
若section不存在,則會報錯configparser.NoSectionError: No section: XXX

2.9、寫入內容
ConfigParserObject.write(open(filename, 'w'))
對configparser對象執行的一些修改操作,必須重新寫回到文件才可生效

示例:

配置文件default.txt

1 [first]
2     name="yusheng_liang"
3     age=20
4     sex = "man"
5 
6 [second]
7     name="june"
8     age=25
9     sex = "weman"

python代碼實現:

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 import configparser
 5 
 6 con = configparser.ConfigParser()
 7 #con對象的read功能,打開文件讀取文件,放進內存
 8 con.read("default.txt", encoding='utf-8')
 9 
10 #1、con對象的sections,內存中所有的節點
11 result = con.sections()
12 print("所有的節點:", result)
13 
14 #2、獲取指定節點下的所有鍵值對
15 con_items = con.items("first")
16 print('first下所有的鍵值對:', con_items)
17 
18 #3、獲取指定節點下的所有鍵
19 ret = con.options("second")
20 print('second下的所有鍵:', ret)
21 
22 #4、獲取指定節點下指定的key的值
23 v = con.get("second", 'age')
24 print('second節點下age的值:', v)
25 
26 #5、檢查、刪除、添加節點
27 #5.1檢查是否存在指定的節點,返回True為存在,False為不存在
28 has_con = con.has_section("first")
29 print('是否已存在first節點:', has_con)
30 #5.2添加節點
31 con.add_section("SEC-1")
32 #con.write(open('default.txt', 'w'))
33 #5.3刪除節點
34 con.remove_section("SEC-1")
35 #con.write(open('default.txt', 'w'))
36 
37 #6、檢查、刪除、設置指定組內的鍵值對
38 #6.1檢查
39 has_opt = con.has_option('second', 'age')
40 print(has_opt)
41 #6.2刪除
42 con.remove_option('second', 'age')
43 #6.3設置
44 con.set('second', 'name', "june_liang")
45 #對configparser對象執行的一些修改操作,必須重新寫回到文件才可生效
46 con.write(open('default.txt', 'w'))
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM