python向config、ini文件读取写入

时间:2021-06-13 19:31:46
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

import configparser
import os class ReadConifg():
"""读取配置文件"""
def __init__(self, filename, filepath):
os.chdir(filepath) # 将当前工作目录切换到指定的目录
self.cf = configparser.ConfigParser() # 实例化configparser对象
self.cf.read(filename) # 读取文件 def read_sections(self):
"""读取配置文件中sections"""
sacs = self.cf.sections() # 获取sections,返回list
print("sections:", sacs, type(sacs)) def read_options(self, sections):
"""获取配置文件中的options值"""
opts = self.cf.options(sections) # 获取db section下的options,返回list
print("%s:%s" % (sections, opts), type(opts)) def read_kv(self, sections):
"""获取配置文件中的所有键值对"""
kvs = self.cf.items(sections) # 获取db section下的所有键值对,返回list
print("%s:%s" % (sections, kvs)) def get_str(self, sections, key):
"""获取指定sectons中指定的key的value值, 返回的会是 str 类型"""
value_str = self.cf.get(sections, key)
return value_str def get_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)
class WriteConfig():
"""写入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) def add_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() def remove_section(self, section):
"""移除section值"""
self.cf.remove_section(section)
self._with_file() def remove_option(self, section, option):
"""移除option值"""
self.cf.remove_option(section, option)
self._with_file()

写入config文件