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 相关文章推荐
推荐11个实用Python库
Jan 23 Python
Python xlrd读取excel日期类型的2种方法
Apr 28 Python
Python实现数据库并行读取和写入实例
Jun 09 Python
django进阶之cookie和session的使用示例
Aug 17 Python
opencv python 图像轮廓/检测轮廓/绘制轮廓的方法
Jul 03 Python
python3 dict ndarray 存成json,并保留原数据精度的实例
Dec 06 Python
Python实现Wordcloud生成词云图的示例
Mar 30 Python
tensorflow指定CPU与GPU运算的方法实现
Apr 21 Python
python实现数字炸弹游戏程序
Jul 17 Python
python使用列表的最佳方案
Aug 12 Python
手把手教你将Flask应用封装成Docker服务的实现
Aug 19 Python
python 监控logcat关键字功能
Sep 04 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入门教程 精简版
2009/12/13 PHP
常用PHP框架功能对照表
2014/10/23 PHP
微信支付开发订单查询实例
2016/07/12 PHP
验证坐标在某坐标区域内php代码
2016/10/08 PHP
jQuery的Ajax时无响应数据的解决方法
2010/05/25 Javascript
JQuery判断子iframe何时加载完成解决方案
2013/08/20 Javascript
js中如何复制一个对象并获取其所有属性和属性对应的值
2013/10/24 Javascript
jQuery源码解读之removeAttr()方法分析
2015/02/20 Javascript
jQuery实现鼠标经过时出现隐藏层文字链接的方法
2015/10/12 Javascript
浅谈JS中的bind方法与函数柯里化
2016/08/10 Javascript
Javascript6中字符串的四个新用法分享
2016/09/11 Javascript
bootstrap实现每隔5秒自动轮播效果
2016/12/20 Javascript
require.js中的define函数详解
2017/07/10 Javascript
基于打包工具Webpack进行项目开发实例
2018/05/29 Javascript
jQuery插件实现弹性运动完整示例
2018/07/07 jQuery
vue下history模式刷新后404错误解决方法
2018/08/18 Javascript
深入理解react 组件类型及使用场景
2019/03/07 Javascript
如何实现小程序tab栏下划线动画效果
2019/05/18 Javascript
vue双向绑定数据限制长度的方法
2019/11/04 Javascript
vue.js实现简单的计算器功能
2020/02/22 Javascript
python使用PyFetion来发送短信的例子
2014/04/22 Python
PyCharm代码整体缩进,反向缩进的方法
2018/06/25 Python
Python中字符串String的基本内置函数与过滤字符模块函数的基本用法
2019/05/27 Python
Python实用库 PrettyTable 学习笔记
2019/08/06 Python
Python叠加矩形框图层2种方法及效果
2020/06/18 Python
Python如何重新加载模块
2020/07/29 Python
HTML5中的新元素介绍
2008/10/17 HTML / CSS
Html5在手机端调用相机的方法实现
2020/05/13 HTML / CSS
倩碧美国官网:Clinique美国
2016/07/20 全球购物
小区停车场管理制度
2014/01/27 职场文书
五好家庭事迹材料
2014/12/20 职场文书
舞出我人生观后感
2015/06/16 职场文书
迎国庆主题班会
2015/08/17 职场文书
2015年教师党员个人总结
2015/11/24 职场文书
在python中实现导入一个需要传参的模块
2021/05/12 Python
Python实现的扫码工具居然这么好用!
2021/06/07 Python