# 示例代码:使用 Python 的 configparser 模块读取和写入配置文件
# 首先,创建一个配置文件 example.cfg
"""
example.cfg 内容如下:
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = hg
[topsecret.server.com]
Port = 50022
ForwardX11 = no
"""
# 读取配置文件
import configparser
config = configparser.ConfigParser()
config.read('example.cfg')
# 获取配置信息
print(config.sections()) # 输出: ['bitbucket.org', 'topsecret.server.com']
print('bytebong.com' in config) # 输出: False
print(config['bitbucket.org']['User']) # 输出: hg
print(config['DEFAULT']['Compression']) # 输出: yes
# 修改配置文件
config['topsecret.server.com']['Port'] = '60022'
# 添加新的 section 和值
config['DEFAULT']['Timeout'] = '30'
with open('example.cfg', 'w') as configfile:
config.write(configfile)
# 解释说明:
# 1. 使用 configparser 模块可以方便地读取和写入 INI 格式的配置文件。
# 2. ConfigParser 对象可以解析配置文件,并提供字典类似的接口来访问配置项。
# 3. 可以通过修改配置对象中的值并调用 write 方法将更改保存回文件。
上一篇:python 日期转字符串
下一篇:python 日期加一天
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站