PYTHON 模块 - configparser

1.1 configparser 模块

这个模块是用于解析配置文件

1.1.1 配置文件的格式

[section]
key = value
key = value
...

[section]
key = value
key = value
...

1.2 读取信息

# comment info
# ...

[db]
host = 127.0.0.1
port = 69
user = admin
password = admin

[info]
message =

1.2.1 读取文件

import configparser

filename = "config.ini"

# 实例化
config = configparser.ConfigParser()
# 读取
config.read(filename, encoding='utf-8')

1.2.2 读取章节

import configparser

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

# sections()返回章节标题组成的列表
sections = config.sections()
print(sections) # ['db', 'info']

1.2.3 读取特定的章节信息

值 = config.get("章节标题","属性名")

指定章节名称和其中的一个属性名称,返回值。

注意:返回的值已经去掉空白

import configparser

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

print(config.get("db", "host"))  # 127.0.0.1
print(config.get("info", "message"))

1.3 写入信息

可以写入信息,之后保存到配置文件中。

1.3.1 添加一个章节

先打开读取再写入,否则会覆盖文件

import configparser

filename = "config.ini"
config = configparser.ConfigParser()
# 先读取文件到内存
config.read(filename, encoding='utf-8')

# 再写入章节属性
config['debug'] = {
    'filename':'log.txt'
}

config.write(open(filename, mode='w'))

结果如下:

[db]
host = 127.0.0.1
port = 69
user = admin
password = admin

[info]
message = 

[debug]
filename = log.txt

1.3.2 在指定的章节里添加一个属性

import configparser

filename = "config.ini"
config = configparser.ConfigParser()
# 先读取文件
config.read(filename, encoding='utf-8')

config["debug"]["level"] = "ERROR"
config.write(open(filename, mode='w'))

结果会增加:

[debug]
filename = log.txt
level = ERROR

1.4 删除信息

可以删除属性及章节

1.4.1 删除属性

import configparser

filename = "config.ini"
config = configparser.ConfigParser()
# 先读取文件
config.read(filename, encoding='utf-8')

# 删除属性debug中的level
config.remove_option("debug","level")

config.write(open(filename, mode='w'))

1.4.2 删除章节

import configparser

filename = "config.ini"
config = configparser.ConfigParser()
# 先读取文件
config.read(filename, encoding='utf-8')

# 删除章节
config.remove_section("debug")

config.write(open(filename, mode='w'))

1.5 修改

config.set("章节","属性","新值")

如:

import configparser

filename = "config.ini"
config = configparser.ConfigParser()
# 先读取文件
config.read(filename, encoding='utf-8')

config.set("info","message","hello!")

config.write(open(filename, mode='w'))

1.6 遍历

1.6.1 遍历一个章节中的所有属性名

import configparser

filename = "config.ini"
config = configparser.ConfigParser()
# 先读取文件
config.read(filename, encoding='utf-8')
for key in config["db"]:
    print(key)
    

# 功能同上,都是遍历key的
for key in config.options("db"):
    print(key)

输出:

host
port
user
password

1.6.1 遍历一个章节中的所有键值

import configparser

filename = "config.ini"
config = configparser.ConfigParser()
# 先读取文件
config.read(filename, encoding='utf-8')
for key,value in config["db"].items():
    print(key,value)
posted @ 2022-12-18 13:09  叁只小羊  阅读(52)  评论(0)    收藏  举报