python操作配置文件

  1. 目的
    一、练习类使用
    二、练习配置文件操作
  2. config.ini
[login]
uname = root
passwd = 123456

[test]
a = 2
b = 3

[my]
dd = sd
gg = 个

[del]
a=dcds
cs=sdcsd
  1. config.py
# !/usr/bin/env/python3
# _*_coding:utf-8_*_
# @__Data__:2020-06-02
# @__Auther__:lalone
# @__PythonVersion__:python3
# @__name__:config.py

import os
import sys

try:
	import configparser
except Exception as e:
	sys.exit("pip install configparser")
try:
	from configobj import ConfigObj
except Exception as e:
	sys.exit("pip install configobj")

class Config(object):
	"""
	@ 操作配置文件
	@ fname : 操作文件名称(必需)
	@ option : 配置文件中的项 eg:[DEFAULT]
	@ name : 配置项的key
	@ value : 配置项的value
	@ option_content : 写入新项所需 eg:{'key':'value'}
	"""
	def __init__(self, fname, option='', name='', value='', option_content={}):
		# super(config, self).__init__()
		curpath = os.path.dirname(os.path.realpath(__file__))
		self._path = os.path.join(curpath, fname)
		self.conf = configparser.ConfigParser()
		self.option = option
		self.name = name
		self.value = value
		self.option_content = option_content

	# 获取所有 sections 名称
	def get_sections(self):
		'''
		@ return : list
		'''
		conf = self.conf

		try:
			conf.read(self._path, encoding='utf-8')
		except Exception as e:
			print(e)
			sys.exit(self._path + "不存在或权限不足")
		
		sections = conf.sections()

		return sections

	# 读取文件
	def _read(self):
		try:
			conf = ConfigObj(self._path, encoding='utf-8')
		except Exception as e:
			print(e)
			sys.exit(self._path + "不存在或权限不足")
		else:
			return conf

	# 获取 option 下所有配置
	def get_options(self):
		'''
		@ param : 
			option : string
		@ return : dict
		'''
		conf = self._read()
		try:
			res = conf[self.option]
			return res
		except Exception as e:
			print(e)
			sys.exit(self.option + "不存在")
		
	# 添加新的 option 
	def set_options(self):
		'''
		@ param : 
			option : string
			option_content : dict
		@ return : bool
		'''
		conf = self._read()
		try:
			conf[self.option] = {}
			for k,v in self.option_content.items():
				conf[self.option][k] = v
			conf.write()
			return True
		except Exception as e:
			print(e)
			sys.exit(self.option + "添加失败")

	# 删除 option 
	def del_options(self):
		'''
		@ param : 
			option : string
		@ return : bool
		'''
		conf = self._read()
		try:
			del conf[self.option]
			conf.write()
			return True
		except Exception as e:
			print(e)
			sys.exit(self.option + "删除失败")

	# 配置文件读取
	def config_read(self):
		'''
		@ param : 
			option : string
			name : string
		@ return : string
		'''
		conf = self._read()
		try:
			res = conf[self.option][self.name]
			return res
		except Exception as e:
			print(e)
			sys.exit(self.option + '>' + self.name + "不存在")

	# 配置文件删除内容
	def config_del(self):
		'''
		@ param : 
			option : string
			name : string
		@ return : bool
		'''
		conf = self._read()
		try:
			del conf[self.option][self.name]
			return True
		except Exception as e:
			print(e)
			sys.exit(self.option + '>' + self.name + "删除失败")

	# 配置文件修改
	def config_set(self):
		'''
		@ param : 
			option : string
			name : string
			value : string
		@ return : bool
		'''
		conf = self._read()
		try:
			conf[self.option][self.name] = self.value
			conf.write()
			return True
		except Exception as e:
			print(e)
			sys.exit(self.option + '>' + self.name + "删除失败")

if __name__ == '__main__':
	test = Config('config.ini')
	print(test.get_sections())

	# test = Config('config.ini','login')
	# print(test.get_options())

	# 废物方法,用处大不
	# test = Config('config.ini','del')
	# print(test.del_options())

	# 废物方法,用处大不
	# test = Config('config.ini','t',option_content={'key':'value'})
	# print(test.set_options())

	# test = Config('config.ini','login','uname')
	# print(test.config_read())

	# 废物方法,用处大不
	# test = Config('config.ini','my','dd')
	# print(test.config_del())

	# test = Config('config.ini','test','b','sddfv的')
	# print(test.config_set())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值