标准库模块:ConfigParse

本文介绍了如何利用Python中的ConfigParser模块来创建、修改及删除配置文件中的信息。通过实例展示了配置文件的基本结构,并演示了如何用Python代码生成配置文件,以及如何读取和修改已有的配置文件。

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

用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。

常见文档格式

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
 
[bitbucket.org]
User = hg
 
[topsecret.server.com]
Port = 50022
ForwardX11 = no
conf

文档生成

import configparser

config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45',
                     'Compression': 'yes',
                     'CompressionLevel': '9'}

config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022'  # mutates the parser
topsecret['ForwardX11'] = 'no'  # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
  config.write(configfile)

  文档读、改、删

import configparser
config = configparser.ConfigParser()

config.read('example.ini')

print(config.sections())  #只打印节点
#
print(config['bitbucket.org']['user'])
#
sec=config.remove_section('bitbucket.org')
config.write(open('example.cfg','w'))

 

转载于:https://www.cnblogs.com/q1ang/p/9021664.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值