python 实现 ini文件 增删改查
INI文件是一种常见的配置文件格式,通常用于存储应用程序的配置信息,例如Windows操作系统中的INI文件。在Python中,我们可以使用ConfigParser模块来读取和修改INI文件。
- 读取INI文件
我们可以使用ConfigParser模块的ConfigParser类来读取INI文件中的配置信息。下面是一个示例:
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
# 获取所有的section
sections = config.sections()
print(sections)
# 获取指定section的所有配置项
options = config.options('database')
print(options)
# 获取指定section的指定配置项的值
host = config.get('database', 'host')
port = config.getint('database', 'port')
username = config.get('database', 'username')
password = config.get('database', 'password')
print(host, port, username, password)
- 修改INI文件
我们可以使用ConfigParser模块的ConfigParser类来修改INI文件中的配置信息。下面是一个示例:
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
# 修改指定section的指定配置项的值
config.set('database', 'host', '127.0.0.1')
config.set('database', 'port', '3306')
config.set('database', 'username', 'root')
config.set('database', 'password', '123456')
# 添加一个新的section
config.add_section('log')
config.set('log', 'level', 'debug')
config.set('log', 'file', 'app.log')
# 删除一个section
config.remove_section('smtp')
# 删除一个配置项
config.remove_option('database', 'password')
# 保存修改后的INI文件
with open('config.ini', 'w') as f:
config.write(f)
- 创建INI文件
我们可以使用ConfigParser模块的ConfigParser类来创建INI文件并写入配置信息。下面是一个示例:
import configparser
config = configparser.ConfigParser()
# 添加section和配置项
config.add_section('database')
config.set('database', 'host', '127.0.0.1')
config.set('database', 'port', '3306')
config.set('database', 'username', 'root')
config.set('database', 'password', '123456')
config.add_section('smtp')
config.set('smtp', 'server', 'smtp.example.com')
config.set('smtp', 'port', '25')
config.set('smtp', 'username', 'user@example.com')
config.set('smtp', 'password', '123456')
# 写入INI文件
with open('config.ini', 'w') as f:
config.write(f)
以上就是Python实现INI文件的增删改查的示例代码
原文地址: https://www.cveoy.top/t/topic/fsrO 著作权归作者所有。请勿转载和采集!