Python configparser模块详解:配置文件的生成、读取、删除与修改

Leo
Leo
发布时间:2026-10-14| 5人浏览过
原创

本文详细介绍Python标准库configparser模块的使用方法,涵盖配置文件的生成、读取、删除及修改操作。通过具体代码示例,演示如何初始化配置、读写节点与选项、删除指定Section及Option,以及如何保存更改到文件,帮助开发者高效管理应用配置。

生成配置文件

首先介绍如何生成配置文件。使用configparser模块,可以先实例化ConfigParser对象,并对DEFAULT部分进行初始化赋值,例如设置ServerAliveInterval、Compression和CompressionLevel等默认参数。接着,可以向DEFAULT中追加ForwardX11选项。随后,创建特定的Section如bitbucket.org和topsecret.server.com,并分别为其添加User、Host Port和ForwardX11等配置项。最后,通过open函数以写入模式打开文件,调用config.write方法将配置内容输出到example.ini文件中。


''' 
  生成配置文件
'''
import configparser

config = configparser.ConfigParser()

# 初始化赋值
config["DEFAULT"] = {'ServerAliveInterval': '45',
           'Compression': 'yes',
           'CompressionLevel': '9'}
# 追加
config['DEFAULT']['ForwardX11'] = 'yes'

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

with open('example.ini', 'w') as configfile:
  config.write(configfile)

读取配置文件

接下来演示如何读取配置文件。导入configparser模块后,实例化ConfigParser对象,此时调用sections()可获取当前已存在的Section列表。通过read方法读取example.ini文件后,可以使用defaults()查看默认配置项,例如ServerAliveInterval、Compression等。通过索引访问特定Section和Key,如config['bitbucket.org']["User"]可获取hg,而config["topsecret.server.com"]["host port"]则返回50022。


# 读
import configparser
config = configparser.ConfigParser()
config.sections()
config.read('example.ini')
# {'serveraliveinterval': '45', 'compression': 'yes', 'compressionlevel': '9', 'forwardx11': 'yes'}
print(config.defaults())

# hg
print(config['bitbucket.org']["User"])

# 50022
print(config["topsecret.server.com"]["host port"])

删除配置生成新文件

然后介绍如何删除配置并生成新文件。在读取example.ini后,使用remove_section方法删除指定的Section,例如bitbucket.org。删除操作返回一个布尔值表示是否成功。随后,通过open函数以写入模式打开新文件example.cfg,并调用config.write将修改后的配置写入该新文件,从而实现删除特定Section并保存为新文件的效果。


# 删除(创建一个新文件,并删除 bitbucket.org)
import configparser
config = configparser.ConfigParser()
config.sections()

config.read('example.ini')
rec = config.remove_section("bitbucket.org") # 删除该项
config.write(open("example.cfg","w"))

新文件内容示例

上述删除操作生成的example.cfg文件内容如下:DEFAULT部分保留了ServerAliveInterval、Compression、CompressionLevel和ForwardX11;topsecret.server.com部分保留了Host Port和ForwardX11。注意,bitbucket.org及其所有配置项已被移除。


DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes

topsecret.server.com]
host port = 50022
forwardx11 = no

直接覆盖原文件删除配置

另一种删除方式是直接覆盖原文件。在读取example.ini后,同样使用remove_section删除bitbucket.org。不同之处在于,这里通过open函数以写入模式直接打开原文件example.ini,并调用config.write将修改后的配置写回原文件。这种方式会直接修改原配置文件,删除指定的Section。


# 删除(删除 bitbucket.org)
import configparser
config = configparser.ConfigParser()
config.sections()

config.read('example.ini')
rec = config.remove_section("bitbucket.org") # 删除该项
config.write(open("example.ini","w"))

修改配置文件

最后介绍如何修改配置文件。在读取example.ini后,可以使用add_section方法添加新的Section,例如yuan。接着,使用remove_section删除bitbucket.org,并使用remove_option从topsecret.server.com中删除forwardx11选项。随后,通过set方法为topsecret.server.com添加k1=11111,为yuan添加k2=22222。最后,以写入模式打开new2.ini文件,调用config.write保存所有更改。


import configparser

config = configparser.ConfigParser()

config.read('example.ini') #读文件

config.add_section('yuan') #添加section

config.remove_section('bitbucket.org') #删除section
config.remove_option('topsecret.server.com',"forwardx11") #删除一个配置项

config.set('topsecret.server.com','k1','11111')
config.set('yuan','k2','22222')
with open('new2.ini','w') as f:
   config.write(f)

修改后文件内容示例

修改后的new2.ini文件内容如下:DEFAULT部分保持不变;topsecret.server.com部分保留了Host Port,新增了k1=11111,移除了ForwardX11;新增了yuan部分,包含k2=22222。这展示了configparser模块在灵活管理配置项方面的能力。


[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes

[topsecret.server.com]
host port = 50022
k1 = 11111

[yuan]
k2 = 22222

总结

以上就是Python configparser模块操作配置文件的完整示例,涵盖了生成、读取、删除和修改四大核心功能。希望这些内容能对您的学习有所帮助,也欢迎大家继续支持本站获取更多技术资源。

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。