Python练习篇17-ini文件读写操作

本文介绍如何读写操作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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值