Python操作ini文件

前期说明

项目结构

1
2
3
PythonINIDemo
|-MysqlConfig.ini
|-PythonINIDemo.py

MysqlConfig.ini文件初始内容

1
2
3
4
[prod]
url = jdbc:mysql://localhost:3306/prod
username = prod1
password = prod11

Python操作

查询

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import configparser

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

# 获取所有的section节点
print(config.sections()) # ['prod']

# 获取指定section的所有key
print(config.options("prod")) # ['url', 'username', 'password']

# 根据section与option,获取指定值
print(config.get("prod", "url")) # jdbc:mysql://localhost:3306/prod
print(config.get("prod", "username")) # prod1
print(config.get("prod", "password")) # prod11

# 获取section下所有的option(key, value)
print(config.items("prod")) # [('url', 'jdbc:mysql://localhost:3306/prod'), ('username', 'prod1'), ('password', 'prod11')]

# 检查指定 section/option 是否存在
print(config.has_section("prod")) # True
print(config.has_option("prod", "url")) # True
print(config.has_section("dev")) # False
print(config.has_option("prod", "token")) # False

增改

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import configparser

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

dev_section = "dev"
dev_option = ["url", "username", "password"]
dev_url = "jdbc:mysql://localhost:3306/dev1"
dev_username = "dev1"
dev_password = "dev11"

# 创建section
if not config.has_section(dev_section):
config.add_section(dev_section)

# 创建option
if not config.has_option(dev_section, dev_option[0]):
config.set(dev_section, dev_option[0], dev_url)

# 创建option
if not config.has_option(dev_section, dev_option[1]):
config.set(dev_section, dev_option[1], dev_username)

# 创建option
if not config.has_option(dev_section, dev_option[2]):
config.set(dev_section, dev_option[2], dev_password)

# 修改option(option不存在则创建)
config.set(dev_section, dev_option[2], "update_dev")

# 将变更写入文件
config.write(open("MysqlConfig.ini", "w"))

测试结果(MysqlConfig.ini文件)

1
2
3
4
5
6
7
8
9
[prod]
url = jdbc:mysql://localhost:3306/prod
username = prod1
password = prod11

[dev]
url = jdbc:mysql://localhost:3306/dev1
username = dev1
password = update_dev

删除

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import configparser

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

config.add_section("test")
config.set("test", "url", "testUrl")
config.set("test", "username", "testUserName")

print(config.items("test")) # [('url', 'testUrl'), ('username', 'testUserName')]

# 删除option
config.remove_option("test", "url")
print(config.items("test")) # [('username', 'testUserName')]

# 删除section
config.remove_section("test")
print(config.has_section("test")) # False
作者

Etsu

发布于

2023-03-01

更新于

2023-03-01

许可协议

评论