python--ConfigParser模块

本文介绍了Python中ConfigParser模块的基本用法,包括如何读取配置文件并解析其中的内容,以及如何利用该模块创建新的配置文件。通过两个实例展示了ConfigParser模块在实际应用中的灵活性。

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

ConfigParser模块用于读取配置文件。
配置文件的格式与Windows INI 文件类似,可以包含一个或多个区域(section),每个区域可以有多个配置条目。
这里有个样例配置文件sample.ini, 在 Example 5-16 用到了这个文件:

[book]
title: The Python Standard Library
author: Fredrik Lundh
email: fredrik@pythonware.com
version: 2.0-001115

[ematter]
pages: 250

[hardcopy]
pages: 350


1、 Example 5-16. 使用 ConfigParser 模块

import ConfigParser
import string

config = ConfigParser.ConfigParser()
config.read("sample.ini")
for section in config.sections():
    print section
    for option in config.options(section):
        print " ", option, "=", config.get(section, option)

#结果
book
  title = The Python Standard Library
  author = Fredrik Lundh
  email = fredrik@pythonware.com
  version = 2.0-001115
ematter
  pages = 250
hardcopy
  pages = 350


2、 Example 5-17. 使用 ConfigParser 模块写入配置数据

File: configparser-example-2.py

import ConfigParser
import sys

config = ConfigParser.ConfigParser()
# set a number of parameters
config.add_section("book")config.set("book", "title", "the python standard library")
config.set("book", "author", "fredrik lundh")
config.add_section("ematter")
config.set("ematter", "pages", 250)
# write to screen
config.write(sys.stdout)

#结果
[book]
title = the python standard library
author = fredrik lundh
[ematter]
pages = 250

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值