一、configparser模块是什么

可以用来操作后缀为 .ini 的配置文件;

python标准库(就是python自带的意思,无需安装)

二、configparser模块基本使用

2.1 读取 ini 配置文件

#存在 config.ini 配置文件,内容如下:
[DEFAULT]
excel_path = ../test_cases/case_data.xlsx
log_path = ../logs/test.log
log_level = 1

[email]
user_name = 32@qq.com
password = 123456

使用configparser模块读取配置文件

import configparser

#创建配置文件对象
conf = configparser.ConfigParser()
#读取配置文件
conf.read('config.ini', encoding="utf-8")
#列表方式返回配置文件所有的section
print( conf.sections() )  #结果:['default', 'email']
#列表方式返回配置文件email 这个section下的所有键名称
print( conf.options('email') )  #结果:['user_name', 'password']
#以[(),()]格式返回 email 这个section下的所有键值对
print( conf.items('email') )  #结果:[('user_name', '32@qq.com'), ('password', '123456')]
#使用get方法获取配置文件具体的值,get方法:参数1-->section(节) 参数2-->key(键名)
value = conf.get('default', 'excel_path')
print(value)

2.2 写入 ini 配置文件(字典形式)

import configparser

#创建配置文件对象
conf = configparser.ConfigParser()
#'DEFAULT'为section的名称,值中的字典为section下的键值对
conf["DEFAULT"] = {'excel_path' : '../test_cases/case_data.xlsx' , 'log_path' : '../logs/test.log'}
conf["email"] = {'user_name':'32@qq.com','password':'123456'}
#把设置的conf对象内容写入config.ini文件
with open('config.ini', 'w') as configfile:
  conf.write(configfile)

2.3 写入 ini 配置文件(方法形式)

import configparser

#创建配置文件对象
conf = configparser.ConfigParser()
#读取配置文件
conf.read('config.ini', encoding="utf-8")
#在conf对象中新增section
conf.add_section('webserver')
#在section对象中新增键值对
conf.set('webserver','ip','127.0.0.1')
conf.set('webserver','port','80')
#修改'DEFAULT'中键为'log_path'的值,如没有该键,则新建
conf.set('DEFAULT','log_path','test.log')
#删除指定section
conf.remove_section('email')
#删除指定键值对
conf.remove_option('DEFAULT','excel_path')
#写入config.ini文件
with open('config.ini', 'w') as f:
  conf.write(f)

上述3个例子基本阐述了configparser模块的核心功能项;

  • 例1中,encoding="utf-8"为了放置读取的适合中文乱码;
  • 例2你可以理解为在字典中新增数据,键:配置文件的section,字符串格式;值:section的键值对,字典格式;
  • 例3中在使用add_section方法时,如果配置文件存在section,则会报错;而set方法在使用时,有则修改,无则新建。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

标签:
Python,configparser模块

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
白云城资源网 Copyright www.dyhadc.com

评论“Python configparser模块应用过程解析”

暂无“Python configparser模块应用过程解析”评论...

RTX 5090要首发 性能要翻倍!三星展示GDDR7显存

三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。

首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。

据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。