文件格式:
[Title1]
key1 = 1111111111
key2 = 2222222222
[Title2]
key1 = 1111111111
key2 = 2222222222
一、python读文件
import configparser cfp = configparser.ConfigParser() cfp.read("test.ini") '''获取所有的selections''' selections = cfp.sections() print(selections) # ['Title1', 'Title2'] '''获取指定selections下的所有options''' options = cfp.options("Title1") print(options) # ['key1', 'key2'] '''获取指定selection下的指定option的值''' value= cfp.get("Title1", "key1") print(value) # 1111111111 '''判断是否含有指定selection 或 option''' print(cfp.has_section("Title1")) # True print(cfp.has_option("Title1", "key3")) # False
二、写文件
代码如下(示例):
import configparser cfp = configparser.ConfigParser() cfp.read("test.ini") cfp.add_section("Title3") # 设置option的值 cfp.set("Title3", "key1", "1111111111") # 注意这里的selection一定要先存在! cfp.set("Title3", "key2", "2222222222") cfp.remove_section("Title3") # 移除指定selection cfp.remove_option("Title2", "key1") # 移除指定selection下的option with open("test.ini", "w+") as f: cfp.write(f)
三、封装成函数
# 将name,password写入ini文件中 def writeToINI(self, name, password): self.config.set('Titlel', name, password) self.config.write(open("Title1.ini", 'w')) # 保存数据 # 读取ini文件中的name,password def readINI(self,name,password): ret = False self.config.read("test.ini") sections = self.config.sections() items = self.config.items('test') # 判断name,password是否存在ini文件的section中 if (name, password) in items: ret = True return ret
注意:
如果某个section已经存在了,在写入的时候不能够再使用config.add_section(‘Title1’)这个函数了,这样会报错,所以,我们需要进行判断,先判断Title1是否存在,然后再进行操作
例子:
self.config = configparser.ConfigParser() # 类实例化 self.config.read('name_password.ini') if 'name_password' not in self.config.sections(): self.config.add_section('name_password')
这样就可以再name_password 这个section下面进行追加操作了。