Python configparser模块读取与写入配置文件详解

巷口听风
巷口听风
发布时间:2026-10-16 | 6人浏览过
原创

本文详细介绍Python标准库configparser的使用。涵盖通过get方法和下标方式读取.ini/.conf文件,演示如何写入配置文件,以及add_section、remove_section等Section操作。同时讲解has_option、set等Option操作,展示将配置值转换为int、float、boolean类型的方法,并提供完整代码示例。

1 使用get方法读取.ini配置文件内容

首先,准备一个名为env.ini的配置文件,其内容如下所示:

[server]
ip=192.168.1.200
port=22
username=root
password=root

[personal]
name=redrose2100
city=nanjing
github=redrose2100.github.io

接下来,编写用于解析该.ini配置文件的Python代码:

import configparser

config=configparser.ConfigParser()
config.read("env.ini","utf-8")


print(config.get("server","ip"))
print(config.get("personal","name"))

运行上述代码后,输出结果如下:

192.168.1.200 redrose2100

2 使用数组下标方式读取.ini配置文件内容

此处使用的env.ini文件内容与前述第1部分保持一致。

通过数组下标方式读取配置文件内容的代码如下:

import configparser

config=configparser.ConfigParser()
config.read("env.ini","utf-8")


print(config["server"]["ip"])
print(config["personal"]["name"])

执行该代码后的结果如下:

192.168.1.200 redrose2100

3 使用configparser写入配置文件

import configparser

config=configparser.ConfigParser()

config["server"]={
    "ip":"192.138.1.200",
    "port":22,
    "username":"root",
    "password":"root"
}

config["personal"]={
    "name":"redrose2100",
    "city":"nanjing"
}

with open("test.ini","w") as f:
    config.write(f)

执行上述代码后,当前目录下会生成一个test.ini文件,其具体内容如下:

[server]
ip = 192.138.1.200
port = 22
username = root
password = root

[personal]
name = redrose2100
city = nanjing

4 configparser对Section(节)的常用操作

  • (1)has_section(section):判断读取的config对象中是否包含指定的section。
  • (2)sections():获取读取到的config对象中所有section的列表。
  • (3)add_section(section):向读取到的config对象中添加一个新的section。需要注意的是,此时添加的section仅存在于config对象中,并未写入到实际的ini配置文件中。
  • (4)remove_section(section):从读取到的config对象中删除指定的section。

相关实例代码如下所示:

import configparser

config=configparser.ConfigParser()
config.read("env.ini","utf-8")
print(config.has_section("server"))
print(config.sections())
config.add_section("kafka")
print(config.sections())
config.remove_section("kafka")
print(config.sections())

运行上述代码后的结果如下:

import configparser

config=configparser.ConfigParser() config.read("env.ini","utf-8") print(config.has_section("server")) print(config.sections()) config.add_section("kafka") print(config.sections()) config.remove_section("kafka") print(config.sections())

5 configparser对Option(选项)的常用操作,代码如下演示:

import configparser

config=configparser.ConfigParser()
config.read("env.ini","utf-8")
print(config.has_option("server","ip"))
print(config.options("server"))
config.set("server","test","test")
print(config.options("server"))
config.remove_option("server","test")
print(config.options("server"))

执行上述代码后的结果为:

True ['ip', 'port', 'username', 'password'] ['ip', 'port', 'username', 'password', 'test'] ['ip', 'port', 'username', 'password']

6 configparser对象可类似字典使用,但其类型并非字典,代码演示如下:

import configparser

config=configparser.ConfigParser()
config.read("env.ini","utf-8")

for key in config["server"].keys():
    print(key)

for key,value in config["server"].items():
    print(key,value)

for value in config["server"].values():
    print(value)

item=config["server"].popitem()
print(type(item))
print(item)

port=config["server"].pop("port")
print(port)

for key,value in config["server"].items():
    print(key,value)

username=config["server"].get("username","no found")
print(username)

print(type(config["server"]))

运行上述代码后的结果如下:

ip port username password ip 192.168.1.200 port 22 username root password root 192.168.1.200 22 root root <class 'tuple'> ('ip', '192.168.1.200') 22 username root password root root <class 'configparser.SectionProxy'>

7 可将获取的配置值直接转换为期望的数据类型,可用的转换方法包括:

  • getint
  • getboolean
  • getfloat
  • get

下面将配置文件更新为如下内容:

[server]
ip=192.168.1.200
port=22
username=root
password=root
is_linux=True
price=100.24

[personal]
name=redrose2100
city=nanjing
github=redrose2100.github.io

实例代码如下:

import configparser

config=configparser.ConfigParser()
config.read("env.ini","utf-8")

ip=config["server"].get("ip")
port=config["server"].getint("port")
is_linux=config["server"].getboolean("is_linux")
price=config["server"].getfloat("price")
print(ip,type(ip))
print(port,type(port))
print(is_linux,type(is_linux))
print(price,type(price))

运行上述代码后的结果如下:

192.168.1.200 <class 'str'> 22 <class 'int'> True <class 'bool'> 100.24 <class 'float'>

8 configparser标准库解析.conf文件与解析.ini文件的方法完全相同,下面仅演示部分操作:

创建一个env.conf文件,其内容如下:

[server]
ip=192.168.1.200
port=22
username=root
password=root
is_linux=True
price=100.24

[personal]
name=redrose2100
city=nanjing
github=redrose2100.github.io

编写如下代码进行解析:

import configparser


config=configparser.ConfigParser()
config.read("env.conf","utf-8")


print(config.get("server","ip"))
print(config.get("personal","name"))

print(config["server"]["ip"])
print(config["personal"]["name"])

运行上述代码后的结果如下:

192.168.1.200 redrose2100 192.168.1.200 redrose2100

到此这篇关于Python configparser模块的用法的文章就介绍到这了,更多相关Python configparser模块内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表