本文介绍如何读写操作ini文件
首先我们需要下载第三方包:configparser(下载方法:打开cmd,输入pip install 包名)
写个类封装ini文件的读写方法
代码如下:
import configparser as cp #导入configparser模块
#封装一个类方法
class RWini(object):
def __init__(self, file_name):
self.c = cp.ConfigParser()
self.file = file_name #ini文件路径
self.c.read(self.file, encoding='utf-8') #设置编码
#写入section,key和value
def write_ini(self, sect, key, value):
if sect in self.c.sections():
print('已存在节点:%s' % sect)
self.c.set(sect, key, value)
with open(self.file, 'w', encoding='utf-8') as f:
self.c.write(f)
print('写入成功!')
else:
self.c.add_section(sect)
self.c.set(sect, key, value)
with open(self.file, 'w', encoding='utf-8') as f:
self.c.write(f)
print('写入成功!')
#以字典形式读取所有内容
def read_ini_all(self):
item_dict = {}
sections = self.c.sections()
for section in sections:
items = self.c.items(section)
item_dict[section] = items
return item_dict
#读去对应节点的key的值
def read_ini_value(self, sect, key):
i = 0
if sect in self.c.sections():
for keys in self.c.items(sect):
i += 1
if key in keys[0]:
return self.c.items(sect)[i-1][1]
else:
print('key:%s错误' % key)
else:
print('节点:%s错误' % sect)
if __name__ == '__main__':
#执行
ini = RWini('test.ini')
ini.write_ini('section1', 'age', '18')
print(ini.read_ini_value('section', 'name'))
print(ini.read_ini_all())
执行结果如下:
写入成功!
Tom
{'section': [('name', 'Tom')], 'section1': [('age', '18')]}
加上ini文件如下:
[section]
name = Tom
[section1]
age = 18