python操作ini类型配置文件的实例教程


Posted in Python onOctober 30, 2020

一、ini文件介绍

INI文件格式是某些平台或软件上的配置文件的非正式标准,以节(section)和键(key)构成,常用于微软Windows操作系统中。这种配置文件的文件扩展名多为INI

二、ini文件的结构

  • 片段[section]
  • 键名 option
  • 值 value

三、实例:

实例1

python25.ini

[teachers]
name = ['yushen', 'pianpian']
age = 16
gender = '女'
favor = {"movie": "追风", "music": "周杰伦"}

[student]
name = ['啦啦迷弟', '啦啦迷妹']
age = 18

操作ini文件

from configparser import ConfigParser

# 初始化
config = ConfigParser()

# 读取文件
config.read('python25.ini', encoding='utf-8')

a = config.get('teachers', 'name')
print(a)
print(type(a))

运行结果如下:

python操作ini类型配置文件的实例教程

实例2

fz.ini

python操作ini类型配置文件的实例教程

读取fz.ini文件代码:

import configparser
import os

curpath = os.path.dirname(os.path.realpath(__file__))
cfgpath = os.path.join(curpath, "fz.ini")

# fz.ini的路径
print(cfgpath)

# 创建管理对象
conf = configparser.ConfigParser()

# 读ini文件
conf.read(cfgpath, encoding="utf-8")


# 获取所有的section
sections = conf.sections()
# 返回list
print(sections)

items = conf.items('oracle')
# list里面对象是元祖
print(items)

运行结果:

python操作ini类型配置文件的实例教程

实例3,封装升级

set修改,add添加,write写入、remove删除

此封装实现以下功能:

  • 获取sections列表
  • 获取指定的section的options列表
  • 获取指定section的配置信息列表
  • 按类型读取配置信息
  • 新增section
  • 设置指定option值
  • 删除指定section
  • 删除指定option
# -*- coding:utf-8 -*-

from configparser import ConfigParser
import os


class TEINI:
 def __init__(self, path):
  self.path = path
  self.ini = ConfigParser()
  self.ini.read(self.path)


 # 获取sections列表
 def get_sections(self):
  if self.ini:
   return self.ini.sections()

 # 获取指定的section的options列表
 def get_options_by_section(self, section):
  if self.ini:
   return self.ini.options(section)

 # 获取指定section的配置信息列表
 def get_section_items(self, section):
  if self.ini:
   return self.ini.items(section)

 # 按类型读取配置信息
 # 返回字符串类型
 def get_string(self, section, option):
  if self.ini:
   return self.ini.get(section, option)

 # 返回int类型
 def get_int(self, section, option):
  if self.ini:
   return self.ini.getint(section, option)

 # 返回float类型
 def get_float(self, section, option):
  if self.ini:
   return self.ini.getfloat(section, option)

 # 返回bool类型
 def get_boolean(self, section, option):
  if self.ini:
   return self.ini.getboolean(section, option)

 # 新增section
 def add_section(self, section):
  if self.ini:
   self.ini.add_section(section)
   self.ini.write(open(self.path, "w"))

 # 设置指定option值
 def set_option(self, section, option, value):
  if self.ini:
   self.ini.set(section, option, value)
   self.ini.write(open(self.path, "w"))

 # 删除指定section
 def remove_section(self, section):
  if self.ini:
   self.ini.remove_section(section)
   self.ini.write(open(self.path, "w"))

 # 删除指定option
 def remove_option(self, section, option):
  if self.ini:
   self.ini.remove_option(section, option)
   self.ini.write(open(self.path, "w"))


if __name__ == "__main__":
 print("python ini标准库解析实例======根据需求运行代码!!!")

 # 如果存在mysql.ini先删除,方便下列代码的运行
 if os.path.exists("mysql.ini"):
  os.remove("mysql.ini")

 # 我们先写一些数据到mysql.ini中
 ini = TEINI("mysql.ini")

 # 先加一个mysql section
 mysql_section = "mysql"
 ini.add_section(mysql_section)

 # 在mysql section下写入一些配置信息
 ini.set_option(mysql_section, "host", "192.168.3.1")
 ini.set_option(mysql_section, "port", "3306")
 ini.set_option(mysql_section, "db", "mysql")
 ini.set_option(mysql_section, "user", "admin")
 ini.set_option(mysql_section, "password", "111111")

 # 再添加一个oracle section
 oracle_section = "oracle"
 ini.add_section(oracle_section)

 # oracle section下写入一些配置信息
 ini.set_option(oracle_section, "host", "192.172.0.1")
 ini.set_option(oracle_section, "port", "8080")
 ini.set_option(oracle_section, "db", "oracle")
 ini.set_option(oracle_section, "user", "guiyin")
 ini.set_option(oracle_section, "password", "666666")

 # 获取下所有的section,并在console输出
 sections = ini.get_sections()
 print(sections)

 # 遍历各个section下的options,并在console中输出
 print("===" * 20)
 for sec in sections:
  print(sec, " 中的options为: ")
  options = ini.get_options_by_section(sec)
  print(options)
  print("===" * 20)

 # 获取各个section下的配置信息
 for sec in sections:
  print(sec, " 中的配置信息为: ")
  items = ini.get_section_items(sec)
  print(items)
  print("***" * 20)

 # 获取指定的option值这里演示读取host和port
 host = ini.get_string("mysql", "host")
 port = ini.get_int("mysql", "port")
 print("类型: ", type(host), " ", type(port))
 print(host, " ", port)

 # 删除mysql中的host配置
 ini.remove_option("mysql", "host")

 # 删除oracle section
 ini.remove_section("oracle")

 # 修改mysql port的值为4000
 ini.set_option("mysql", "port", "5538")


 # 最终mysql.ini中的文件内容如下
 # [mysql]
 # port = 5538
 # db = mysql
 # user = admin
 # password = 111111
items = ini.get_section_items("mysql")
print(items)
print("!!!" * 20)

运行结果如下:

python操作ini类型配置文件的实例教程

总结 

到此这篇关于python操作ini类型配置文件的文章就介绍到这了,更多相关python操作ini类型配置文件内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Eclipse + Python 的安装与配置流程
Mar 05 Python
python读取csv文件示例(python操作csv)
Mar 11 Python
Python中subprocess模块用法实例详解
May 20 Python
python3 模拟登录v2ex实例讲解
Jul 13 Python
python矩阵转换为一维数组的实例
Jun 05 Python
Python实现模拟浏览器请求及会话保持操作示例
Jul 30 Python
对python中的try、except、finally 执行顺序详解
Feb 18 Python
python pygame实现方向键控制小球
May 17 Python
python写日志文件操作类与应用示例
Jul 01 Python
Python List列表对象内置方法实例详解
Oct 22 Python
PYTHON如何读取和写入EXCEL里面的数据
Oct 28 Python
MxNet预训练模型到Pytorch模型的转换方式
May 25 Python
4款Python 类型检查工具,你选择哪个呢?
Oct 30 #Python
python从PDF中提取数据的示例
Oct 30 #Python
详解python百行有效代码实现汉诺塔小游戏(简约版)
Oct 30 #Python
python boto和boto3操作bucket的示例
Oct 30 #Python
python 多进程和协程配合使用写入数据
Oct 30 #Python
python打包生成so文件的实现
Oct 30 #Python
pytorch 移动端部署之helloworld的使用
Oct 30 #Python
You might like
php 什么是PEAR?(第二篇)
2009/03/19 PHP
ECMall支持SSL连接邮件服务器的配置方法详解
2014/05/19 PHP
php 伪静态之IIS篇
2014/06/02 PHP
PHP中使用匿名函数操作数据库的例子
2014/11/17 PHP
PHP生成指定范围内的N个不重复的随机数
2019/03/18 PHP
javascript实现的listview效果
2007/04/28 Javascript
checkbox 多选框 联动实现代码
2008/10/22 Javascript
JavaScript中使用构造函数实现继承的代码
2010/08/12 Javascript
字符串的replace方法应用浅析
2011/12/06 Javascript
Javascript模仿淘宝信用评价实例(附源码)
2015/11/26 Javascript
JavaScript登录验证码的实现
2016/10/27 Javascript
Vue.Js中的$watch()方法总结
2017/03/23 Javascript
Bootstrap table学习笔记(2) 前后端分页模糊查询
2017/05/18 Javascript
浅谈Vue 初始化性能优化
2017/08/31 Javascript
详解Js中的模块化是如何实现的
2017/10/18 Javascript
Vue EventBus自定义组件事件传递
2018/06/25 Javascript
JS合并两个数组的3种方法详解
2019/10/24 Javascript
微信小程序中的video视频实现 自定义播放按钮、封面图、视频封面上文案
2020/01/02 Javascript
深入分析JavaScript 事件循环(Event Loop)
2020/06/19 Javascript
[07:31]DOTA2卡尔工作室 英雄介绍主宰篇
2013/06/25 DOTA
[02:20]DOTA2亚洲邀请赛 EHOME战队出场宣传片
2015/02/07 DOTA
[01:03]悬念揭晓 11月26日DOTA2完美盛典不见不散
2017/11/23 DOTA
分享Python文本生成二维码实例
2016/01/06 Python
Python正则捕获操作示例
2017/08/19 Python
python中scikit-learn机器代码实例
2018/08/05 Python
pytorch在fintune时将sequential中的层输出方法,以vgg为例
2019/08/20 Python
python 求10个数的平均数实例
2019/12/16 Python
使用python tkinter开发一个爬取B站直播弹幕工具的实现代码
2021/02/07 Python
html5 application cache遇到的严重问题
2012/12/26 HTML / CSS
New Balance美国官网:运动鞋和健身服装
2017/04/11 全球购物
idealfit英国:世界领先的女性健身用品和运动衣物品牌
2017/11/25 全球购物
大学校园活动策划书
2014/02/04 职场文书
服装区域经理岗位职责
2015/04/10 职场文书
2015年乡镇残联工作总结
2015/05/13 职场文书
环保守法证明
2015/06/24 职场文书
结婚典礼主持词
2015/06/29 职场文书