INI文件由节、键、值组成。格式如下:
例如:
[section]
name=value
name:value
注解使用分号表示(;)。在分号后面的文字,直到该行结尾都全部为注解。
configparser模块含有configparser类,主要包含三个模块:RawConfigParser(),ConfigParser()、SafeConfigParse()这三个方法(三选一),创建一个对象使用对象的方法对配置文件进行增删改查操作.
from configparser import ConfigParser
if __name__ == "__main__":
#写入数据到test.ini文件
config=ConfigParser()
config.add_section('login')
config.set('login','name','test')
config.set('login','paw','test')
with open("test.ini",'w+') as f :
config.write(f)
with open("test.ini",'r') as f_read:
config.read_file(f_read)
print(config.get('login','name'))
config.read(f_read)
#获取section
print(config.sections())
#获取key
print(config.get('login','name'))
#获取value
print(config.get('login','paw'))
#获取某个section下的key,value
print(config.options('login'))
#判断section是否存在,存在返回True,不存在返回False
print(config.has_section('login'))
#方法判断section下,某个键是否存在,存在返回True,不存在返回False
print(config.has_option('login','name1'))
删除
remove_section()方法删除某个section,remove_option()方法删除某个section下的键
config.remove_section('login','paw')
注:要先read到内存
config.read(file)
实际删除的为内存中的,文件中的section的键不会减少