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 相关文章推荐
Python标准库内置函数complex介绍
Nov 25 Python
Python简单获取自身外网IP的方法
Sep 18 Python
pygame实现弹力球及其变速效果
Jul 03 Python
Python编程实现及时获取新邮件的方法示例
Aug 10 Python
Python 获得13位unix时间戳的方法
Oct 20 Python
python使用正则表达式的search()函数实现指定位置搜索功能
Nov 10 Python
对python中的logger模块全面讲解
Apr 28 Python
pytorch 把MNIST数据集转换成图片和txt的方法
May 20 Python
python将txt文档每行内容循环插入数据库的方法
Dec 28 Python
python的faker库用法
Nov 28 Python
在Python中用GDAL实现矢量对栅格的切割实例
Mar 11 Python
教你怎么用Python操作MySql数据库
May 31 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+Ajax实时自动检测是否联网的方法
2015/07/01 PHP
PHP设计模式之模板方法模式定义与用法详解
2018/04/02 PHP
laravel7学习之无限级分类的最新实现方法
2020/09/30 PHP
JavaScript网页制作特殊效果用随机数
2007/05/22 Javascript
利用404错误页面实现UrlRewrite的实现代码
2008/08/20 Javascript
使用AngularJS实现可伸缩的页面切换的方法
2015/06/19 Javascript
jQuery form插件的使用之处理server返回的JSON, XML,HTML数据
2016/01/26 Javascript
Windows 系统下设置Nodejs NPM全局路径
2016/04/26 NodeJs
微信小程序上滑加载下拉刷新(onscrollLower)分批加载数据(二)
2017/05/11 Javascript
EasyUI的DataGrid绑定Json数据源的示例代码
2017/12/16 Javascript
jQuery实现参数自定义的文字跑马灯效果
2018/08/15 jQuery
浅谈ECMAScript 中的Array类型
2019/06/10 Javascript
layui之table checkbox初始化时选中对应选项的方法
2019/09/02 Javascript
python使用WMI检测windows系统信息、硬盘信息、网卡信息的方法
2015/05/15 Python
Python中map,reduce,filter和sorted函数的使用方法
2015/08/17 Python
Python基于pygame实现的font游戏字体(附源码)
2015/11/11 Python
Python中Class类用法实例分析
2015/11/12 Python
详解python并发获取snmp信息及性能测试
2017/03/27 Python
Python 中Pickle库的使用详解
2018/02/24 Python
Python编程在flask中模拟进行Restful的CRUD操作
2018/12/28 Python
详解字符串在Python内部是如何省内存的
2020/02/03 Python
浅谈pandas dataframe对除数是零的处理
2020/07/20 Python
requests在python中发送请求的实例讲解
2021/02/17 Python
英国鹦鹉店:Parrot Essentials
2018/12/03 全球购物
员工生日会策划方案
2014/06/14 职场文书
经贸日语专业自荐信
2014/09/02 职场文书
学校联谊协议书
2014/09/16 职场文书
交通事故死亡赔偿协议书
2014/12/03 职场文书
小学重阳节活动总结
2015/03/24 职场文书
2015教师个人德育工作总结
2015/07/22 职场文书
安全生产奖惩制度
2015/08/06 职场文书
小学三年级作文之写景
2019/11/05 职场文书
Python文件的操作示例的详细讲解
2021/04/08 Python
详解Vue的sync修饰符
2021/05/15 Vue.js
JavaScript事件的委托(代理)的用法示例详解
2022/02/18 Javascript
vue实现简易音乐播放器
2022/08/14 Vue.js