Python读取配置文件详解:INI、YAML与XML格式实战

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

本文详细介绍Python中读取INI、YAML和XML三种常见配置文件的方法。通过ConfigParser、PyYAML及xml.dom.minidom模块,演示如何解析键值对、嵌套结构及引用语法,并提供完整代码示例,帮助开发者高效管理项目配置。

前言与配置文件概述

零、前言

在Python开发中,配置文件是不可或缺的一部分。常见的配置文件格式包括INI、YAML、XML、Properties、TXT以及Python脚本文件等。

INI配置文件解析

一、INI文件

1.1 INI文件的格式

; 注释内容

[url] ; section名称 baidu = https://www.jb51.net port = 80

[email] sender = 'xxx@qq.com'

需要注意的是,Section(节)的名称不能重复,且注释必须以分号开头。

1.2 读取 configparser

Python内置的configparser模块可用于读取.ini文件。需要注意的是,在Python 2中该模块名为ConfigParser(首字母大写)。

创建配置文件时,只需在PyCharm等编辑器中创建一个扩展名为.ini的文件即可。


import configparser

file = 'config.ini'

# 创建配置文件对象
con = configparser.ConfigParser()

# 读取文件
con.read(file, encoding='utf-8')

# 获取所有section
sections = con.sections()
# ['url', 'email']


# 获取特定section
items = con.items('url') # 返回结果为元组
# [('baidu','https://www.jb51.net'),('port', '80')] # 数字也默认读取为字符串

# 可以通过dict方法转换为字典
items = dict(items)

YAML配置文件详解

二、YAML配置文件

2.1 YAML文件格式

YAML是一种旨在方便读写的数据序列化格式,本质上是一种通用的数据串行化标准。

其基本语法规则如下:

大小写敏感。

使用缩进表示层级关系。

缩进时禁止使用Tab键,仅允许使用空格。

空格数量不限,但相同层级的元素必须严格对齐。

使用#表示注释,#号后的所有字符将被忽略。

YAML支持的数据格式包括:

字典、数组以及纯量(单个且不可再分割的值)。

2.1.2 对象

对象由一组键值对组成,使用冒号分隔键与值。


url: https://www.jb51.net
log: 
 file_name: test.log
 backup_count: 5

YAML也支持另一种写法,即将所有键值对写在一行内,称为行内对象。

log: {file_name: test.log, backup_count: 5}

2.1.3 数组

由以横线开头的多行组成一个数组。

- cat - Dog - Goldfish

转换为Python对象后为:

['cat', 'Dog', 'Goldfish']

数组也可以采用行内写法:

animal: [cat, dog]

转换为Python对象后为:

{'animal': ['cat', 'dog']}

2.1.4 纯量

纯量是最基本且不可分割的值。

数字和字符串可以直接书写:

number: 12.30 name: zhangsan

布尔值使用true和false表示。

isSet: true flag: false

空值使用~表示。

parent: ~

YAML允许使用两个感叹号表示强制类型转换。

e: !!str 123 f: !!str true

2.1.5 引用

锚点&和别名*可用于引用已有数据。


defaults: &defaults
 adapter: postgres
 host: localhost
 
development: 
 databases: myapp_deveploment
 <<: *defaults

test:
 databases: myapp_test
 <<: *defaults

这等同于以下展开后的代码结构。


defaults: 
 adapter: postgres
 host: localhost
 
development: 
 databases: myapp_deveploment
 adapter: postgres
 host: localhost

test:
 databases: myapp_test
 adapter: postgres
 host: localhost

&用于建立锚点(如defaults),<<表示将数据合并到当前节点,*用于引用锚点。

下面是另一个示例:

- &abc st - cat - dog - *abc

转换为Python列表后为:

['st', 'cat', 'dog', 'st']

2.2 YAML文件的读取

读取YAML文件前需先安装相应的第三方模块。

pip install yaml

YAML文件内容示例如下:


url: https://www.baidu.com
email:
 send: xxx@qq.com
 port: 25

---
url: http://www.sina.com.cn

读取代码如下:


# coding:utf-8
import yaml

# 获取yaml文件路径
yamlPath = 'config.yaml'

with open(yamlPath,'rb') as f:
 # yaml文件通过---分节,多个节组合成一个列表
 date = yaml.safe_load_all(f)
 # salf_load_all方法得到的是一个迭代器,需要使用list()方法转换为列表
 print(list(date))

XML配置文件读取

三、XML配置文件读取

XML文件内容示例如下:


<collection shelf="New Arrivals">
<movie title="Enemy Behind">
 <type>War, Thriller</type>
 <format>DVD</format>
 <year>2003</year>
 <rating>PG</rating>
 <stars>10</stars>
 <description>Talk about a US-Japan war</description>
</movie>
<movie title="Transformers">
 <type>Anime, Science Fiction</type>
 <format>DVD</format>
 <year>1989</year>
 <rating>R</rating>
 <stars>8</stars>
 <description>A schientific fiction</description>
</movie>
 <movie title="Trigun">
 <type>Anime, Action</type>
 <format>DVD</format>
 <episodes>4</episodes>
 <rating>PG</rating>
 <stars>10</stars>
 <description>Vash the Stampede!</description>
</movie>
<movie title="Ishtar">
 <type>Comedy</type>
 <format>VHS</format>
 <rating>PG</rating>
 <stars>2</stars>
 <description>Viewable boredom</description>
</movie>
</collection>

读取代码如下:


# coding=utf-8
import xml.dom.minidom
from xml.dom.minidom import parse

DOMTree = parse('config.xml')
collection = DOMTree.documentElement
if collection.hasAttribute("shelf"):
 print("Root element : %s" % collection.getAttribute("shelf"))

# 在集合中获取所有电影
movies = collection.getElementsByTagName("movie")

# 打印每部电影的详细信息
for movie in movies:
 print("*****Movie*****")
 if movie.hasAttribute("title"):
  print("Title: %s" % movie.getAttribute("title"))

 type = movie.getElementsByTagName('type')[0]
 print("Type: %s" % type.childNodes[0].data)
 format = movie.getElementsByTagName('format')[0]
 print("Format: %s" % format.childNodes[0].data)
 rating = movie.getElementsByTagName('rating')[0]
 print("Rating: %s" % rating.childNodes[0].data)
 description = movie.getElementsByTagName('description')[0]
 print("Description: %s" % description.childNodes[0].data)

以上关于Python读取配置文件(INI、YAML、XML)的内容即为分享的全部,希望能对大家有所帮助,也欢迎多多支持本站。

相关标签:

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

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 算法库。