Python configparser读取cfg配置文件里的内容

本文介绍如何使用Python的configparser模块来读取CFG配置文件,并展示了具体的代码实例。通过实例可以看到configparser可以方便地获取配置文件中指定部分的内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python configparser读取cfg配置文件里的内容

标题config.cfg中的内容

[detector]

weights=weights/yolov5s.pt
source=rtmp://172.28.188.139:1935/mylive1/test
source_mp4=crossline.mp4
img-size=640
conf_thres=0.6
iou_thres=0.45
device=0
augment=False
classes=None

读取文件中的内容

import configparser

cfg = configparser.ConfigParser()
cfg.read('config.cfg')
weight_path = cfg.get('detector','weights')
print(weight_path)

>>weights/yolov5s.pt
### PythonCFG 配置文件的创建与读取 #### 创建 CFG 文件Python 中,`ConfigParser` 模块提供了方便的方法来处理 `.cfg` 或其他类型的配置文件。为了创建一个 `cfg` 文件,在项目目录结构中建立一个新的配置文件并编写相应的键值对。 ```ini # config.cfg [DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User = hg [topsecret.server.com] Port = 50022 ForwardX11 = no ``` 此段代码展示了如何构建一个简单的 `cfg` 文件[^2]。 #### 使用 ConfigParser 读取 CFG 文件读取上述创建好的配置文件,需先导入 `configparser` 库,并初始化一个 `ConfigParser` 对象实例化之后加载指定路径下的配置文件: ```python import configparser # 初始化配置解析器对象 config = configparser.ConfigParser() # 加载配置文件 config.read('path/to/config.cfg') # 获取特定部分中的选项值 server_alive_interval = config.getint('DEFAULT', 'ServerAliveInterval') compression_level = config.getint('DEFAULT', 'CompressionLevel') forward_x11_bitbucket = config.getboolean('bitbucket.org', 'ForwardX11') port_topsecret = config.getint('topsecret.server.com', 'Port') print(f"Server Alive Interval: {server_alive_interval}") print(f"Compression Level: {compression_level}") print(f"Bitbucket Forward X11: {'Yes' if forward_x11_bitbucket else 'No'}") print(f"Top Secret Server Port: {port_topsecret}") ``` 这段脚本演示了怎样利用 `ConfigParser` 类从已有的 `cfg` 文件提取数据。 #### 修改和保存 CFG 文件 除了读取之外,还可以修改现有的设置并将更改回存到磁盘上: ```python # 更新现有条目 config.set('DEFAULT', 'ServerAliveInterval', str(60)) with open('path/to/config.cfg', 'w') as configfile: config.write(configfile) ``` 这允许动态调整应用程序的行为而无需重新编译源码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值