Python configparser模块配置文件过程解析

作者:lxingchen 时间:2023-03-04 09:35:49 

ConfigParser模块在Python3修改为configparser,这个模块定义了一个ConfigeParser类,该类的作用是让配置文件生效。配置文件的格式和window的ini文件相同

编辑配置文件: .ini

模板:内容自定义

一、 编辑配置文件


import configparser

config = configparser.ConfigParser()
config['DEFAULT'] = {
 'ServerAliveInterval':'45',
 'Compression':'yes',
 'CompressionLevel':'9',
 'ForwardX11':'yes'
}
config['bitbucker.org'] = {
 'Host Port':'50022',
 'ForwardX11':'no'
}
config['path'] = {
 'Base_Path':'D:\python\pychrom\路飞学城\day8',
 'student_path':'D:\python\pychrom\路飞学城\day8\configparser模块.py'
}

with open('example.ini','w',encoding='utf-8') as configfile:
 config.write(configfile)

二、读取配置文件


import configparser

config = configparser.ConfigParser()
config.read('example.ini',encoding='utf-8')

print(config.sections())      # 查看分组情况,默认default是不显示的
print('bitbucker.org' in config)   # Flase 判断一个组在不在这个文件当中
print('bitbucker.com' in config)   # True

print(config['bitbucker.org']['host_port']) # 查钊这个文件中这个分组下面有没有这个配置
print(config['bitbucker.org']['user'])    # 没有就报错

for key in config['bitbucker.org']:      # 取默认分组和这个组的下面所有配置
 print(key)                # 只能取到 key

print(config.options('bitbucker.org'))     # 取分组下面的配置,包括默认分组 只能取到值
print(config.items('bitbucker.org'))       # 取到分组下面的键值对,包括默认分组

print(config.get('path','base_path'))       # 获取某个分组下面的键来获取值

三、增删改查


import configparser
config = configparser.ConfigParser()
config.read('example.ini',encoding='utf-8')
config.add_section('zuming')    # 添加组
config.remove_section('zuming')   # 删除一个组
config.remove_option('bitbucker.org','host_port')  # 删除某个组中的某一项
config.set('bitbucker.org','host_port','22')  # 修改某个组下面的值
config.write(open('example.ini','w',encoding='utf-8'))  # 必须添加这句话才能生效

来源:https://www.cnblogs.com/lxc123/p/12398971.html

标签:Python,configparser,模块
0
投稿

猜你喜欢

  • 3个用于数据科学的顶级Python库

    2022-09-25 15:26:45
  • 基于Python数据结构之递归与回溯搜索

    2022-02-27 01:40:33
  • 使用Django和Python创建Json response的方法

    2022-04-28 13:08:42
  • Python中super()函数简介及用法分享

    2021-09-23 11:56:22
  • python实现移位加密和解密

    2022-03-20 09:09:27
  • 自动生成sql语句

    2008-05-09 12:42:00
  • sql server not in 语句使程充崩溃

    2012-01-05 19:05:00
  • Python实现统计代码行的方法分析

    2023-10-15 13:08:44
  • 5分钟教会你用Docker部署一个Python应用

    2023-11-12 10:24:09
  • OpenCV-Python实现通用形态学函数

    2022-02-13 18:10:33
  • python使用matplotlib绘制折线图教程

    2022-06-28 11:26:37
  • JS阻止事件冒泡的方法详解

    2023-09-10 08:57:36
  • javascript 通用滑动门tab类

    2023-08-05 09:42:25
  • 快速了解Python开发中的cookie及简单代码示例

    2023-05-29 11:04:05
  • Python中隐藏的五种实用技巧分享

    2023-08-23 15:12:05
  • 使用OpenCV实现仿射变换—平移功能

    2022-11-01 01:45:06
  • MySQL学习之数据库操作DML详解小白篇

    2024-01-14 11:59:48
  • git stash的正确用法详解

    2022-11-06 19:10:07
  • python 画三维图像 曲面图和散点图的示例

    2022-04-13 01:28:16
  • 微信小程序前端自定义分享的实现方法

    2024-05-02 16:13:35
  • asp之家 网络编程 m.aspxhome.com