本文描述常几种配置文件。
所有内容都可以直接通过AI获取。
JSON
代码案例(一看便知):(AI给的,我没想写这么社畜的)
json
{
"用户数据": {
"基本信息": {
"姓名": "张三",
"年龄": 28,
"是否活跃": true,
"薪资": 12000.75,
"入职日期": "2020-01-15",
"备注": null
},
"技能列表": [
"Python",
"JavaScript",
"Java"
],
"工作经历": [
{
"公司": "科技公司A",
"职位": "软件工程师",
"年限": 2
},
{
"公司": "科技公司B",
"职位": "高级工程师",
"年限": 1
}
],
"联系方式": {
"邮箱": "zhangsan@example.com",
"电话": "13800138000",
"地址": {
"省份": "广东省",
"城市": "深圳市",
"详细地址": "南山区科技园"
}
},
"项目统计": {
"总项目数": 10,
"完成项目数": 8,
"进行中项目数": 2
}
}
}
特点:
-
不能有注释
-
数字:整数、浮点数
-
bool: true or false
-
字符串"xx"
-
空值null
-
键值对以
:连接 -
键必须是字符串,用双引号包围
-
不同键值对之间以
,分隔 -
?对象?:使用花括号 {} 包裹的键值对集合,如 {"姓名": "张三", "年龄": 25}
-
数组?:使用方括号 [] 包裹的有序列表,如 ["Python", "Java", "C++"]
-
对象和数组之间,可以自身或互相无限嵌套
INI
INI(Initialization File)
ini
[database]
host = localhost
port = 3306
username = root
password = secret123
[application]
name = MyApp
debug = true
采用"[Section]"+"key=value"结构- 支持注释,注释以
#或:开头 - 所有值均为字符串类型
YAML
YAML(YAML Ain't Markup Language)是一种人类友好的数据序列化标准,常用于配置文件和数据交换。
- 使用缩进表示层级。
- 支持多种数据类型(字符串、数字、布尔值、列表、字典等)。
- 使用 # 添加注释。
- 大小写敏感。
yaml
database:
host: localhost
port: 3306
credentials:
user: root
password: secret123
application:
name: MyApp
debug: true
XML
XML(eXtensible Markup Language)是一种标记语言,常用于企业级应用和Web服务中。
- 使用标签(
<tag>)表示结构。 - 支持嵌套和属性。
- 有严格的语法结构。
xml
<configuration>
<database>
<host>localhost</host>
<port>3306</port>
<credentials>
<user>root</user>
<password>secret123</password>
</credentials>
</database>
<application>
<name>MyApp</name>
<debug>true</debug>
</application>
</configuration>
Properties
Properties 文件通常用于 Java 应用程序中,格式简单,键值对以 key=value 形式表示。
语法特点:
- 键值对格式为 key=value。
- 支持注释(以 # 或 ! 开头)。
- 值可以包含特殊字符,需转义。
properties
database.host=localhost
database.port=3306
database.user=root
database.password=secret123
application.name=MyApp
application.debug=true
TOML
TOML(Tom's Obvious, Minimal Language)是一种旨在易于阅读和编写的配置文件格式,支持多种数据类型。
toml
# 这是一个展示TOML所有主要特性的配置文件示例
# 1. 基本键值对
title = "TOML 示例配置文件"
version = 1.0
enabled = true
# 2. 字符串类型
name = "配置文件示例"
description = """
这是一个多行字符串示例,
用来展示TOML对复杂文本的支持。
"""
# 3. 数字类型
integer_value = 42
float_value = 3.14159
scientific_notation = 1e+10
# 4. 日期时间类型
current_date = 2026-03-06
current_datetime = 2026-03-06T20:40:12Z
local_datetime = 2026-03-06T20:40:12
local_time = 20:40:12
# 5. 数组类型
numbers = [1, 2, 3, 4, 5]
strings = ["apple", "banana", "cherry"]
mixed_array = [1, "two", 3.0, true]
# 6. 内联表
simple_point = { x = 1, y = 2 }
complex_info = { name = "example", active = true, count = 42 }
# 7. 表(节)
[database]
server = "192.168.1.1"
ports = [8001, 8001, 8002]
connection_max = 5000
enabled = true
# 8. 嵌套表
[database.credentials]
username = "admin"
password = "secret123"
token = "abc123xyz"
# 9. 数组表(表数组)
[[products]]
name = "笔记本电脑"
sku = "LP-2026"
price = 5999.99
[[products]]
name = "无线鼠标"
sku = "WM-2026"
price = 199.99
[[products]]
name = "机械键盘"
sku = "MK-2026"
price = 399.99
# 10. 复杂嵌套结构
[servers]
alpha.ip = "10.0.0.1"
alpha.role = "frontend"
beta.ip = "10.0.0.2"
beta.role = "backend"
toml和ini很像,但有所区别
- 支持字符串、整数、浮点数、布尔值、日期时间、数组等,类型明确
- 使用 = 分隔键值对。
- 注释(#)。
- 不使用缩进表示层级。
python读取或导出配置文件
对于 JSON 格式的配置文件,Python 的 json 模块会将其解析为字典(dict)和列表(list)对象。例如,JSON 对象会被转换为 Python 字典,JSON 数组会被转换为 Python 列表。
对于 INI 格式的配置文件,Python 的 configparser 模块会将其解析为 ConfigParser 对象,该对象提供了类似字典的接口,但内部结构是分节(section)的,每个节又包含键值对。
对于 YAML 格式的配置文件,通常使用 PyYAML 库进行解析,它会将 YAML 内容转换为 Python 的字典、列表等原生数据类型。
对于 Properties 格式的配置文件,Python 的 configparser 模块也可以处理,但通常会将其视为简单的键值对集合。
python
import json
import configparser
import xml.etree.ElementTree as ET
import xml.dom.minidom as minidom
from typing import Dict, Any, Union
def read_json_config(file_path: str) -> Union[Dict[str, Any], None]:
"""读取JSON格式配置文件"""
try:
with open(file_path, 'r', encoding='utf-8') as f:
config = json.load(f)
return config
except FileNotFoundError:
print(f"错误: 找不到文件 {file_path}")
return None
except json.JSONDecodeError as e:
print(f"JSON格式错误: {e}")
return None
def write_json_config(file_path: str, data: Dict[str, Any]) -> bool:
"""写入JSON格式配置文件"""
try:
with open(file_path, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
print(f"JSON配置已保存到 {file_path}")
return True
except Exception as e:
print(f"写入JSON文件失败: {e}")
return False
def read_ini_config(file_path: str) -> Union[configparser.ConfigParser, None]:
"""读取INI格式配置文件"""
config = configparser.ConfigParser()
try:
config.read(file_path, encoding='utf-8')
return config
except FileNotFoundError:
print(f"错误: 找不到文件 {file_path}")
return None
except Exception as e:
print(f"读取INI文件失败: {e}")
return None
def write_ini_config(file_path: str, data: Dict[str, Dict[str, str]]) -> bool:
"""写入INI格式配置文件"""
config = configparser.ConfigParser()
# 将字典数据转换为INI格式
for section, section_data in data.items():
config[section] = section_data
try:
with open(file_path, 'w', encoding='utf-8') as f:
config.write(f)
print(f"INI配置已保存到 {file_path}")
return True
except Exception as e:
print(f"写入INI文件失败: {e}")
return False
def read_xml_config(file_path: str) -> Union[ET.Element, None]:
"""读取XML格式配置文件"""
try:
tree = ET.parse(file_path)
root = tree.getroot()
return root
except FileNotFoundError:
print(f"错误: 找不到文件 {file_path}")
return None
except ET.ParseError as e:
print(f"XML解析错误: {e}")
return None
def write_xml_config(file_path: str, root: ET.Element) -> bool:
"""写入XML格式配置文件"""
try:
# 格式化XML输出
rough_string = ET.tostring(root, encoding='utf-8')
reparsed = minidom.parseString(rough_string)
pretty_xml = reparsed.toprettyxml(indent=" ", encoding='utf-8')
with open(file_path, 'wb') as f:
f.write(pretty_xml)
print(f"XML配置已保存到 {file_path}")
return True
except Exception as e:
print(f"写入XML文件失败: {e}")
return False
def xml_to_dict(element: ET.Element) -> Dict[str, Any]:
"""将XML元素转换为字典"""
result = {}
# 处理元素属性
if element.attrib:
result['@attributes'] = element.attrib
# 处理子元素
children = list(element)
if children:
child_dict = {}
for child in children:
child_data = xml_to_dict(child)
if child.tag in child_dict:
# 如果标签已存在,转换为列表
if not isinstance(child_dict[child.tag], list):
child_dict[child.tag] = [child_dict[child.tag]]
child_dict[child.tag].append(child_data)
else:
child_dict[child.tag] = child_data
result.update(child_dict)
# 处理文本内容
if element.text and element.text.strip():
if result:
result['#text'] = element.text.strip()
else:
return element.text.strip()
return result if result else None
def dict_to_xml(tag: str, data: Dict[str, Any]) -> ET.Element:
"""将字典转换为XML元素"""
elem = ET.Element(tag)
for key, value in data.items():
if key == '@attributes':
elem.attrib.update(value)
elif key == '#text':
elem.text = str(value)
elif isinstance(value, dict):
child = dict_to_xml(key, value)
elem.append(child)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
child = dict_to_xml(key, item)
elem.append(child)
else:
child = ET.Element(key)
child.text = str(item)
elem.append(child)
else:
child = ET.Element(key)
child.text = str(value)
elem.append(child)
return elem
def read_yaml_config(file_path: str) -> Union[Dict[str, Any], None]:
"""读取YAML格式配置文件"""
try:
import yaml
with open(file_path, 'r', encoding='utf-8') as f:
config = yaml.safe_load(f)
return config
except ImportError:
print("错误: 需要安装PyYAML库 (pip install PyYAML)")
return None
except FileNotFoundError:
print(f"错误: 找不到文件 {file_path}")
return None
except Exception as e:
print(f"读取YAML文件失败: {e}")
return None
def write_yaml_config(file_path: str, data: Dict[str, Any]) -> bool:
"""写入YAML格式配置文件"""
try:
import yaml
with open(file_path, 'w', encoding='utf-8') as f:
yaml.dump(data, f, allow_unicode=True, default_flow_style=False, indent=2)
print(f"YAML配置已保存到 {file_path}")
return True
except ImportError:
print("错误: 需要安装PyYAML库 (pip install PyYAML)")
return False
except Exception as e:
print(f"写入YAML文件失败: {e}")
return False
def read_toml_config(file_path: str) -> Union[Dict[str, Any], None]:
"""读取TOML格式配置文件"""
try:
import toml
with open(file_path, 'r', encoding='utf-8') as f:
config = toml.load(f)
return config
except ImportError:
print("错误: 需要安装toml库 (pip install toml)")
return None
except FileNotFoundError:
print(f"错误: 找不到文件 {file_path}")
return None
except Exception as e:
print(f"读取TOML文件失败: {e}")
return None
def write_toml_config(file_path: str, data: Dict[str, Any]) -> bool:
"""写入TOML格式配置文件"""
try:
import toml
with open(file_path, 'w', encoding='utf-8') as f:
toml.dump(data, f)
print(f"TOML配置已保存到 {file_path}")
return True
except ImportError:
print("错误: 需要安装toml库 (pip install toml)")
return False
except Exception as e:
print(f"写入TOML文件失败: {e}")
return False
def read_properties_config(file_path: str) -> Union[Dict[str, str], None]:
"""读取Properties格式配置文件"""
config = {}
try:
with open(file_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
# 跳过空行和注释
if not line or line.startswith('#') or line.startswith('!'):
continue
# 分割键值对
if '=' in line:
key, value = line.split('=', 1)
elif ':' in line:
key, value = line.split(':', 1)
else:
continue
config[key.strip()] = value.strip()
return config
except FileNotFoundError:
print(f"错误: 找不到文件 {file_path}")
return None
except Exception as e:
print(f"读取Properties文件失败: {e}")
return None
def write_properties_config(file_path: str, data: Dict[str, str]) -> bool:
"""写入Properties格式配置文件"""
try:
with open(file_path, 'w', encoding='utf-8') as f:
for key, value in data.items():
f.write(f"{key}={value}\n")
print(f"Properties配置已保存到 {file_path}")
return True
except Exception as e:
print(f"写入Properties文件失败: {e}")
return False
def demo():
"""演示各类配置文件的读写操作"""
# JSON配置示例
json_data = {
"database": {
"host": "localhost",
"port": 3306,
"username": "admin",
"password": "secret123"
},
"application": {
"name": "MyApp",
"version": "1.0.0",
"debug": True
}
}
# INI配置示例
ini_data = {
"database": {
"host": "localhost",
"port": "3306",
"username": "admin",
"password": "secret123"
},
"application": {
"name": "MyApp",
"version": "1.0.0",
"debug": "true"
}
}
# XML配置示例
xml_root = ET.Element("configuration")
db_elem = ET.SubElement(xml_root, "database")
ET.SubElement(db_elem, "host").text = "localhost"
ET.SubElement(db_elem, "port").text = "3306"
ET.SubElement(db_elem, "username").text = "admin"
ET.SubElement(db_elem, "password").text = "secret123"
app_elem = ET.SubElement(xml_root, "application")
ET.SubElement(app_elem, "name").text = "MyApp"
ET.SubElement(app_elem, "version").text = "1.0.0"
ET.SubElement(app_elem, "debug").text = "true"
# YAML配置示例
yaml_data = {
"database": {
"host": "localhost",
"port": 3306,
"credentials": {
"username": "admin",
"password": "secret123"
}
},
"application": {
"name": "MyApp",
"version": "1.0.0",
"debug": True
}
}
# TOML配置示例
toml_data = {
"database": {
"host": "localhost",
"port": 3306,
"username": "admin",
"password": "secret123"
},
"application": {
"name": "MyApp",
"version": "1.0.0",
"debug": True
}
}
# Properties配置示例
properties_data = {
"database.host": "localhost",
"database.port": "3306",
"database.username": "admin",
"database.password": "secret123",
"application.name": "MyApp",
"application.version": "1.0.0",
"application.debug": "true"
}
print("=== 配置文件写入演示 ===")
# 写入各类配置文件
write_json_config("config.json", json_data)
write_ini_config("config.ini", ini_data)
write_xml_config("config.xml", xml_root)
write_yaml_config("config.yaml", yaml_data)
write_toml_config("config.toml", toml_data)
write_properties_config("config.properties", properties_data)
print("\n=== 配置文件读取演示 ===")
# 读取各类配置文件
print("读取JSON配置:")
json_config = read_json_config("config.json")
if json_config:
print(json_config)
print("\n读取INI配置:")
ini_config = read_ini_config("config.ini")
if ini_config:
for section in ini_config.sections():
print(f"[{section}]")
for key, value in ini_config.items(section):
print(f"{key} = {value}")
print("\n读取XML配置:")
xml_config = read_xml_config("config.xml")
if xml_config:
xml_dict = xml_to_dict(xml_config)
print(xml_dict)
print("\n读取YAML配置:")
yaml_config = read_yaml_config("config.yaml")
if yaml_config:
print(yaml_config)
print("\n读取TOML配置:")
toml_config = read_toml_config("config.toml")
if toml_config:
print(toml_config)
print("\n读取Properties配置:")
properties_config = read_properties_config("config.properties")
if properties_config:
for key, value in properties_config.items():
print(f"{key} = {value}")
if __name__ == "__main__":
demo()