温馨提示×

python configparser模块怎么使用

小亿
90
2023-12-01 21:50:54
栏目: 编程语言

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模块读取和更新配置文件的操作。

0