ConfigParse简介

ConfigParser 在python中是用来解析配置文件的内置模块,直接导入使用

import configparser

使用该模块可以对配置文件进行增、读、改、删操作。

配置文件的文件类型可以为任意文本类型,比如:ini、txt、csv等。

配置文件中可以包含一个或多个区域(section),每个区域可以有多个参数(键=值)。

配置文件的格式如下:

[db]
db_host = 127.0.0.1
db_port = 3306
db_user = root
db_pass = 123456

[account]
username = admin
password = admin

说明:[ ]为section,用来区分不同的区域,section下面的key-value为配置内容。

ConfigParse使用

初始化对象并读取配置

import configparser

# 创建实例对象
config = configparser.ConfigParser() # 读取配置文件
config.clear() # 读取前清除已读内容。若不清除,多次读取文件会出现非预期内容。
file_path = rf'config/config.ini'
config.read(file_path, encoding="utf-8")

新增/修改配置

使用add_section(section)方法添加section

使用set(section, key, value)方法在指定的section下添加或修改key-value,若key不存在,则添加,若key已存在,则修改

# 新增section
section = "login" # 新增section时,若section在配置文件已存在,则会抛错:already exists
if not config.has_section(section):
# 增加section
config.add_section(section) # 增加key-value
config.set(section, 'username', '1111')
config.set(section, 'password', '2222') # 将配置写入文件
with open(file_path, 'w', encording="utf-8") as configfile:
config.write(configfile)

读取配置

可以用读取字典的两种方法读取指定section中指定key的value

# 读取指定section中指定key的value
# 第一种:使用get方法读取
username = config.get('login', 'username')
password = config.get('login', 'password')
print(username, password)
null_section = config.get('login4', 'username', fallback=u'section 不存在') # 若section或option不存在,fallback返回后备值
null_option = config.get('login', 'NoneKey', fallback=u'key 不存在')
print(null_section, ",", null_option) # 第二种:以[]的方式读取
username = config["login"]["username"]
print(username)

除了能获取指定值,还可以用sections()方法读取所有section,读取结果为list

# 读取配置文件所有section
sections = config.sections()
print(sections)

还可以用options()方法读取所有key,读取结果为list

# 读取对应section下所有key
keys = config.options('login')
print(keys)

删除配置

# 删除指定section下的key,key不存不会抛错,但section不存在则抛错:No section,
config.remove_option('login', 'username') # 删除指定section,section不存在不会抛错
config.remove_section('login') # 将操作同步到文件中
with open(file_path, 'w', encoding="utf-8") as configfile:
config.write(configfile)

其他操作

# has_section()方法判断是否存在指定section,存在返回True,不存在返回False
ret = config.has_section('login')
print(ret) # has_option()方法判断指定section下,是否存在指定key,存在返回True,不存在返回False
ret = config.has_option('login', 'username')
print(ret)

ConfigParse拓展

ConfigParse没有将配置文件读取成dict类型的方法,需要处理转换下

# 暂时没有读取出dict格式的配置文件信息的方法,需要自己处理
# 创建实例对象
config = configparser.ConfigParser() # 读取配置文件
config.clear() # 读取前清除已读内容。若不清除,多次读取文件会出现非预期内容。
file_path = rf'config/config.ini'
config.read(file_path, encoding="utf-8") # 转换配置
login_config = config['account']
login_config_dict = dict(login_config)
print(login_config_dict)

读取结果

ConfigParser_读取配置文件信息的更多相关文章

  1. Asp.net Core 和类库读取配置文件信息

    Asp.net Core 和类库读取配置文件信息 看干货请移步至.net core 读取配置文件公共类 首先开一个脑洞,Asp.net core 被使用这么长时间了,但是关于配置文件(json)的读取 ...

  2. 在java中读取配置文件信息

    public class PropertyUtil { public static final Properties PROP = new Properties(); /** * 读取配置文件的内容( ...

  3. spring配置:context:property-placeholder 读取配置文件信息 在配置文件中使用el表达式填充值

    spring将properties文件读取后在配置文件中直接将对象的配置信息填充到bean中的变量里. 原本使用PropertyPlaceholderConfigurer类进行文件信息配置.Prope ...

  4. spring boot 读取配置文件信息

    1.读取application.properties @Component @ConfigurationProperties(prefix="images.product.column&qu ...

  5. SpringBoot | 读取配置文件信息

    server.port=8081 #修改端口号 server.servlet.context-path= /SpringBoot #修改URL #自定义配置 tz.name = xiaoming tz ...

  6. java读取配置文件信息

    ResourceBundle resource = ResourceBundle.getBundle("shopxx");//不要加.properties后缀,我加了报错 reso ...

  7. .NET Core2.1获取自定义配置文件信息

    前言 .net core来势已不可阻挡.既然挡不了,那我们就顺应它.了解它并学习它.今天我们就来看看和之前.net版本的配置文件读取方式有何异同,这里不在赘述.NET Core 基础知识. ps:更新 ...

  8. Asp.NetCore 读取配置文件帮助类

    /// <summary> /// 读取配置文件信息 /// </summary> public class ConfigExtensions { public static ...

  9. 1.selenium实战之从txt文档读取配置信息并执行登录

    前置条件: 1.本机已搭建ECShop3.0网站 2.在脚本目录创建了user.txt文本如下: 目的:实现从txt中读取配置文件信息,本实战中,包含url地址.用户名.密码,然后进行ESChop的登 ...

随机推荐

  1. Spring Cloud 和dubbo

    一.SpringCloud微服务技术简介 Spring Cloud 作为Java 语言的微服务框架,它依赖于Spring Boot,有快速开发.持续交付和容易部署等特点.Spring Cloud 的组 ...

  2. 【科研工具】CAJViewer的一些操作

    逐渐发现CAJViewer没有想象中的难用. 添加书签:Ctrl+M 使用按类分类,可以筛选出书签位置,和注释区分. 搜索:Ctrl+F 可以定义多种搜索.

  3. java中关于string类和常量池的一点猜想

    public class StringTest { /**   * @param args   */  public static void main(String[] args) {   test1 ...

  4. collection库更新1.4.0版本

    collection库更新1.4.0版本 collection库一直在使用中,周末集合github上的反馈以及contributor的修改,更新了1.4.0版本. 这个版本做了几个事情: 增加了三种类 ...

  5. React中使用 react-router-dom 路由传参的三种方式详解【含V5.x、V6.x】!!!

    路由传值的三种方式(v5.x) params参数 //路由链接(携带参数): <Link to='/demo/test/tom/18'}>详情</Link> //或 <L ...

  6. C# VS 断点进不去,显示红色空心右下角黄色感叹号图标

    今天开发同事遇到了一个诡异的问题,使用 Visual Studio 调式 C# 代码时,断电位置一直显示红色空心右下角有黄色感叹号的图标(下图所示),断点调试死活进不去. 几个同事过去看了下,都隐约感 ...

  7. 延时间隔(Project)

    <Project2016 企业项目管理实践>张会斌 董方好 编著 像"饭前洗手"这种事,绝大部分情况下,是洗完手马上就可以动筷子开吃,但总会有意外,比如手都洗好了,突然 ...

  8. CF139A Petr and Book 题解

    Content 小 P 有一本 \(n\) 页的书,现给出他一周七天每天的阅读页数,求它在星期几读完这本书. 数据范围:\(1\leqslant n\leqslant 1000\). Solution ...

  9. CF918B Radio Station 题解

    Content 有 \(n\) 个形如 \(a_i.b_i.c_i.d_i\) 的 IP 地址.有 \(m\) 条命令,每条命令由一条字符串 \(s\) 和一个形如 \(p.q.r.s\) 的 IP ...

  10. 55 道MySQL基础题

    1.一张表,里面有 ID 自增主键,当 insert 了 17 条记录之后, 删除了第 15, 16, 17 条记录,再把 Mysql 重启,再 insert 一条记 录,这条记录的 ID 是 18 ...