import yaml
# 示例代码:读取 YAML 文件并将其转换为 Python 字典
def read_yaml(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
data = yaml.safe_load(file)
return data
# 示例代码:将 Python 字典写入 YAML 文件
def write_yaml(data, file_path):
with open(file_path, 'w', encoding='utf-8') as file:
yaml.dump(data, file, default_flow_style=False, allow_unicode=True)
# 示例数据
data = {
'name': 'Alice',
'age': 30,
'address': {
'street': '123 Main St',
'city': 'Wonderland'
},
'hobbies': ['reading', 'chess', 'traveling']
}
# 写入 YAML 文件
write_yaml(data, 'example.yaml')
# 读取 YAML 文件
loaded_data = read_yaml('example.yaml')
print(loaded_data)
yaml 模块:首先需要导入 yaml 模块,该模块提供了处理 YAML 格式数据的功能。read_yaml 函数打开指定路径的 YAML 文件,并使用 yaml.safe_load 将其内容解析为 Python 字典。write_yaml 函数接受一个 Python 字典和文件路径,使用 yaml.dump 将字典内容写入 YAML 文件。default_flow_style=False 参数确保输出为块样式(block style),allow_unicode=True 允许在输出中包含 Unicode 字符。data。example.yaml 文件,然后读取该文件并打印其内容以验证操作是否成功。希望这段代码和解释对你有帮助!
上一篇:python升级
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站