python configparser模块怎么使用

   2025-02-13 9390
核心提示:Python的configparser模块用于读取配置文件。下面是一个使用configparser模块的例子:首先,创建一个配置文件(config.ini):[D

Python的configparser模块用于读取配置文件。下面是一个使用configparser模块的例子:

首先,创建一个配置文件(config.ini):
[Database]host = localhostport = 3306user = rootpassword = 123456database = test[Logging]level = INFOfile = log.txt
在Python脚本中导入configparser模块,并创建一个配置解析器:
import configparserconfig = configparser.ConfigParser()
使用配置解析器读取配置文件:
config.read('config.ini')
获取配置文件中的值:
# 获取Database部分的配置host = config.get('Database', 'host')port = config.get('Database', 'port')user = config.get('Database', 'user')password = config.get('Database', 'password')database = config.get('Database', 'database')# 获取Logging部分的配置level = config.get('Logging', 'level')file = config.get('Logging', 'file')
可以通过修改配置文件中的值来更新配置:
# 更新Database部分的配置config.set('Database', 'host', 'newhost')config.set('Database', 'port', 'newport')config.set('Database', 'user', 'newuser')config.set('Database', 'password', 'newpassword')config.set('Database', 'database', 'newdatabase')# 更新Logging部分的配置config.set('Logging', 'level', 'DEBUG')config.set('Logging', 'file', 'newlog.txt')# 保存更新后的配置文件with open('config.ini', 'w') as configfile:    config.write(configfile)

这样就完成了使用configparser模块读取和更新配置文件的操作。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言