python对配置文件.ini进行增删改查操作的方法示例

yipeiwu_com6年前Python基础

前言

本文主要给大家介绍的是关于python对配置文件.ini增删改查操作的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍:

一、先导入configobj库文件

可以用pip直接安装

#!/usr/bin/python
# -*- coding: utf-8 -*-

import json

from configobj import ConfigObj

二、增添section

这里是前后端分离的例子,从前端接收json数据,然后写入配置文件中

def add(self, false=None):
 self.log.debug("list")
 try:
  conf_ini = CONFIG_INI_PATH+"users.ini.bak"
  config = ConfigObj(conf_ini, encoding='UTF8')
  req = self.input["input"]
  data = req["data"]
  userName = data["userName"]
  disc = data["disc"]
  ip = data["ip"]
  expMonth = int(float(data["expDate"]) * 12)
  for user in config.items():
   if userName == user[0]:
    self.out = '{"status": 1,"msg":"用户名已存在!"}'
    return false
   else:
    pass
  config[userName] = {}
  config[userName]['user'] = userName
  config[userName]['disc'] = disc
  config[userName]['ip'] = ip
  config[userName]['validity_date'] = data["expDate"]
  config[userName]['cert_expired'] = get_today_month(expMonth)
  config[userName]['enable'] = 0
  config[userName]['path'] = USER_KEY_PATH + userName
  config.write()
  self.out = '{"status": 0,"msg":"操作成功!"}'
 except Exception, e:
  self.out = '{"status":1, "msg":"'+str(e)+'"}'

三、修改section

def modify(self):
 self.log.debug("modify")
 try:
  conf_ini = CONFIG_INI_PATH + "users.ini.bak"
  config = ConfigObj(conf_ini, encoding='UTF8')
  req = self.input["input"]
  data = req["data"]
  userName = data["userName"]
  disc = data["disc"]
  ip = data["ip"]
  config[userName]['disc'] = disc
  config[userName]['ip'] = ip
  config.write()
  self.out = '{"status": 0,"msg":"操作成功!"}'
 except Exception, e:
  self.out = '{"status":1, "msg":"'+str(e)+'"}'

四、删除section

通过section名找到相应section进行del操作

def delete(self, false=None):
 self.log.debug("delete")
 try:
  conf_ini = CONFIG_INI_PATH + "users.ini.bak"
  config = ConfigObj(conf_ini, encoding='UTF8')
  req = self.input["input"]
  data = req["data"]
  userName = data["userName"]
  for user in config.items():
   if userName == user[0]:
    del config[userName]
    config.write()
    self.out = '{"status": 0,"msg":"操作成功!"}'
    return false
   else:
    pass
  self.out = '{"status": 1,"msg":"用户不存在!"}'
 except Exception, e:
  self.out = '{"status":1, "msg":"config err!"}'

五、查询section

这里借用python字典将配置文件里的内容整体输出,代码里还有查询和分页的功能

def list(self):
 self.log.debug("list")
 try:
  req = self.input["input"]
  data = req["data"]
  pageSize = req["pageSize"]
  pageIndex = req["pageIndex"]
  userName = data["userName"]
  conf_ini = CONFIG_INI_PATH + "users.ini.bak"
  config = ConfigObj(conf_ini, encoding='UTF8')
  users = []
  n = 0
  if userName == '':
   for user in config.items():
    n = n + 1
    if pageSize * pageIndex + 1 <= n <= pageSize * (pageIndex + 1):
     users.append(user[1])
    else:
     pass
  else:
   for user in config.items():
    if userName == user[0]:
     n = n + 1
     if pageSize * pageIndex + 1 <= n <= pageSize * (pageIndex + 1):
      users.append(user[1])
     else:
      pass
    else:
     pass

  utext = json.dumps(users)
  self.out = '{"status": 0,"total":'+str(n)+',"data":' + utext + '}'
 except Exception, e:
  self.out = '{"status":1, "msg":"' + str(e) + '"}'
 self.log.debug("list in.")

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对【听图阁-专注于Python设计】的支持

相关文章

Python 从列表中取值和取索引的方法

如下所示: name_list["zhangsan","lisi","wangwu"] #1.取值 print(name_list[0]) print(name_list[1])...

如何在python中实现随机选择

这篇文章主要介绍了如何在python中实现随机选择,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 想从一个序列中随机抽取若干元素,或者...

python中的常量和变量代码详解

局部和全局变量: # name='lhf' # def change_name(): # # global name # name='帅了一比' # print('cha...

Python设置matplotlib.plot的坐标轴刻度间隔以及刻度范围

Python设置matplotlib.plot的坐标轴刻度间隔以及刻度范围

一、用默认设置绘制折线图 import matplotlib.pyplot as plt x_values=list(range(11)) #x轴的数字是0到10这11个整数 y...

Python中的ctime()方法使用教程

 ctime()方法转换,因为历元到表示本地时间的字符串表示以秒为单位的时间。如果不设置秒时或None,所返回的时间的当前time()被使用。使用asctime(localti...