python configparser模块怎么使用

58次阅读
没有评论

共计 1449 个字符,预计需要花费 4 分钟才能阅读完成。

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

  1. 首先,创建一个配置文件(config.ini):
[Database]
host = localhost
port = 3306
user = root
password = 123456
database = test

[Logging]
level = INFO
file = log.txt
  1. 在 Python 脚本中导入 configparser 模块,并创建一个配置解析器:
import configparser

config = configparser.ConfigParser()
  1. 使用配置解析器读取配置文件:
config.read('config.ini')
  1. 获取配置文件中的值:
# 获取 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')
  1. 可以通过修改配置文件中的值来更新配置:
# 更新 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 模块读取和更新配置文件的操作。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-13发表,共计1449字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)