python在__ini写入路径_python向config、ini文件读取写入

config读取操作

cf = configparser.ConfigParser() # 实例化对象

cf.read(filename) # 读取文件

cf.sections() # 读取sections值, 返回一个list

cf.options(sections) # 读取options值, 返回一个list

cf.items(sections) # 读取指定sections下所有的键值对, 返回list

cf.get(sections, key) # 获取指定sections下指定key的value值, 返回str

cf.getint(sections, key) # 获取指定sections下指定key的value值, 返回int

#encoding: utf-8

importconfigparserimportosclassReadConifg():"""读取配置文件"""

def __init__(self, filename, filepath):

os.chdir(filepath)#将当前工作目录切换到指定的目录

self.cf = configparser.ConfigParser() #实例化configparser对象

self.cf.read(filename) #读取文件

defread_sections(self):"""读取配置文件中sections"""sacs= self.cf.sections() #获取sections,返回list

print("sections:", sacs, type(sacs))defread_options(self, sections):"""获取配置文件中的options值"""opts= self.cf.options(sections) #获取db section下的options,返回list

print("%s:%s" %(sections, opts), type(opts))defread_kv(self, sections):"""获取配置文件中的所有键值对"""kvs= self.cf.items(sections) #获取db section下的所有键值对,返回list

print("%s:%s" %(sections, kvs))defget_str(self, sections, key):"""获取指定sectons中指定的key的value值, 返回的会是 str 类型"""value_str=self.cf.get(sections, key)returnvalue_strdefget_int(self, sections, key):"""获取指定sectons中指定的key的value值, 返回的会是 int 类型"""value_int=self.cf.getint(sections, key)return value_int

读取config文件

config写入操作

cf = configparser.ConfigParser() # 实例化对象

cf.read(self.filename) # 读取文件,如果是重新写入,覆盖原有内容不需要读取

cf.add_section(section) # 添加sections值

cf.set(section, option, value) # 在指定的sections中添加键值对

cf.remove_section(section) # 移除sections, 需要先cf.read(filename)

cf.remove_option(section, option) # 移除指定sections下的options, 需要先cf.read(filename)

classWriteConfig():"""写入config文件"""

def __init__(self, filename, filepath=r"D:\python_file\boke\config"):

self.filename=filename

os.chdir(filepath)

self.cf=configparser.ConfigParser()

self.cf.read(self.filename)#如果修改,则必须读原文件

def_with_file(self):#write to file

with open(self.filename, "w+") as f:

self.cf.write(f)defadd_section(self, section):#写入section值

self.cf.add_section(section)

self._with_file()def set_options(self,section, option, value=None):"""写入option值"""self.cf.set(section, option, value)

self._with_file()defremove_section(self, section):"""移除section值"""self.cf.remove_section(section)

self._with_file()defremove_option(self, section, option):"""移除option值"""self.cf.remove_option(section, option)

self._with_file()

写入config文件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值