# 示例代码:使用 Python 的 configparser 模块读取和写入配置文件
# 首先,确保你已经创建了一个配置文件,例如 config.ini
# config.ini 文件内容如下:
"""
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = hg
[topsecret.server.com]
Port = 50022
ForwardX11 = no
"""
import configparser
# 创建一个 ConfigParser 对象
config = configparser.ConfigParser()
# 读取配置文件
config.read('config.ini')
# 获取配置项
print(config.sections()) # 输出: ['bitbucket.org', 'topsecret.server.com']
# 获取特定部分的值
print(config['bitbucket.org']['User']) # 输出: hg
# 修改配置文件中的值
config['topsecret.server.com']['Port'] = '50023'
# 添加新的部分和值
config['DEFAULT']['Timeout'] = '30'
config['new_section'] = {'Host': 'example.com', 'User': 'admin'}
# 将修改后的配置写回文件
with open('config.ini', 'w') as configfile:
config.write(configfile)
# 解释说明:
# 1. 使用 configparser 模块可以方便地读取和写入 INI 格式的配置文件。
# 2. `config.read('config.ini')` 用于读取配置文件。
# 3. `config.sections()` 返回所有部分的名称(不包括 DEFAULT)。
# 4. `config[section][option]` 用于获取或设置特定部分的选项值。
# 5. `config.write(configfile)` 用于将修改后的配置写回文件。
下一篇:python 格式化日期
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站