python的configparser模块

configparser用于处理特定格式的文件,其本质上是利用open来操作文件。

#此为test文件
[section1]
k2 = 1
k1 = qwe

[section2]
k1 = 100
k2 = 200.56
 1 import configparser
 2 
 3 config = configparser.ConfigParser()
 4 config.read('test', encoding='utf-8')
 5 ret = config.sections()     #获取所有节点
 6 print(ret)
 7 ret1 = config.items('section1')     #获取节点section1下的键值对
 8 print(ret1)
 9 ret2 = config.options('section1')   #获取节点section1下的键
10 print(ret2)
11 ret3 = config.get('section1', 'k1')  #获取指定节点下指定键的值
12 print(ret3)
13 ret4 = config.getint('section2', 'k1')   #获取指定节点下指定的键的值,并转化为int型
14 print(ret4)
15 ret5 = config.getfloat('section2', 'k2') #获取指定节点下指定的键的值,并转化为float型
16 print(ret5)
17 ret6 = config.getboolean('section1', 'k2')   #获取指定节点下指定的键的值,并判断是否为布尔值
18 print(ret6)                                 #此处的布尔值支持0、1、true、false,其他都报错
19 
20 has_sec = config.has_section('section3')      #判断是否存在节点section3
21 print(has_sec)
22 config.add_section('section3')         #添加节点section3,此时存在于内存中
23 config.write(open('test', 'w', encoding='utf-8'))     #将其内存的test写进test即可保存在文件中,文件中若存在,则报错
24 config.remove_section('section3')       #删除节点section3,若不存在则报错
25 config.write(open('test', 'w', encoding='utf-8'))     #还可以将内存的test写进其他文件
26 
27 hs = config.has_option('section1', 'k1')      #判断是否存在节点section3的键k1
28 print(hs)
29 config.remove_option('section1', 'k1')       #将节点section1下的键k1删除
30 config.write(open('test', 'w', encoding='utf-8'))
31 config.set('section1', 'k1', 'qwe')         #设置节点section1,键值对为k1:qwe,若section1不存在则报错
32 config.write(open('test', 'w', encoding='utf-8'))
原文地址:https://www.cnblogs.com/caibao666/p/6489456.html