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自动格式化json文件的方法
Mar 11 Python
安装dbus-python的简要教程
May 05 Python
Python使用urllib2模块抓取HTML页面资源的实例分享
May 03 Python
python处理按钮消息的实例详解
Jul 11 Python
浅谈python中的数字类型与处理工具
Aug 02 Python
python3.5 cv2 获取视频特定帧生成jpg图片
Aug 28 Python
Python for循环与getitem的关系详解
Jan 02 Python
Django admin 实现search_fields精确查询实例
Mar 30 Python
python dict如何定义
Sep 02 Python
如何使用 Python 读取文件和照片的创建日期
Sep 05 Python
python中turtle库的简单使用教程
Nov 11 Python
如何判断pytorch是否支持GPU加速
Jun 01 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
第五节--克隆
2006/11/16 PHP
简单的php文件上传(实例)
2013/10/27 PHP
PHP中strncmp()函数比较两个字符串前2个字符是否相等的方法
2016/01/07 PHP
php+redis在实际项目中HTTP 500: Internal Server Error故障排除
2017/02/05 PHP
PHP的反射机制实例详解
2017/03/29 PHP
CentOS7.0下安装PHP5.6.30服务的教程详解
2018/09/29 PHP
在jQuery1.5中使用deferred对象 着放大镜看Promise
2011/03/12 Javascript
JavaScript 创建运动框架的实现代码
2013/05/08 Javascript
JS 获取浏览器和屏幕宽高等信息代码
2014/03/31 Javascript
使用Sticker.js实现贴纸效果
2015/01/28 Javascript
js时钟翻牌效果实现代码分享
2020/07/31 Javascript
jQuery EasyUI基础教程之EasyUI常用组件(推荐)
2016/07/15 Javascript
JS实现六边形3D拖拽翻转效果的方法
2016/09/11 Javascript
JS给swf传参数的实现方法
2016/09/13 Javascript
页面缩放兼容性处理方法(zoom,Firefox火狐浏览器)
2017/08/29 Javascript
Express系列之multer上传的使用
2017/10/27 Javascript
jQuery实现导航样式布局操作示例【可自定义样式布局】
2018/07/24 jQuery
js运算符的一些特殊用法
2018/07/29 Javascript
VUE解决微信签名及SPA微信invalid signature问题(完美处理)
2019/03/29 Javascript
vue解决使用$http获取数据时报错的问题
2019/10/30 Javascript
浅谈vue中$event理解和框架中在包含默认值外传参
2020/08/07 Javascript
vue 导航锚点_点击平滑滚动,导航栏对应变化详解
2020/08/10 Javascript
Python完全新手教程
2007/02/08 Python
Django Highcharts制作图表
2016/08/27 Python
Python通过属性手段实现只允许调用一次的示例讲解
2018/04/21 Python
Django如何将URL映射到视图
2019/07/29 Python
基于python进行抽样分布描述及实践详解
2019/09/02 Python
Python 字符串、列表、元组的截取与切片操作示例
2019/09/17 Python
Django中使用Json返回数据的实现方法
2020/06/03 Python
解决TensorFlow程序无限制占用GPU的方法
2020/06/30 Python
Appium+Python实现简单的自动化登录测试的实现
2021/01/26 Python
金额转换,阿拉伯数字的金额转换成中国传统的形式如:(¥1011)-> (一千零一拾一元整)输出
2015/05/29 面试题
委托函范文
2015/01/29 职场文书
小学元宵节活动总结
2015/02/06 职场文书
防溺水安全教育主题班会
2015/08/12 职场文书
JS代码编译器Monaco使用方法
2021/06/11 Javascript