0
点赞
收藏
分享

微信扫一扫

python 数据写入yaml 文件中文和排序问题

前言

数据写入yaml 文件时遇到的一些问题总结,主要是中文问题和字典的排序问题。

环境准备

python3.8 版本
PyYAML 版本6.0

使用示例

将一段python的字典类型,转成yaml文件

import yaml
# 作者 上海-悠悠

data = {
"get请求": {
"name": "GET请求示例",
"sleep": 3,
"request": {
"method": "GET",
"url": "/get"
}
}
}

# 写入yaml 文件
with open("data.yml", 'w', encoding="utf-8") as fp:
yaml.safe_dump(data, fp, indent=4)

safe_dump 方法默认传2个传参,第一个是需要转的数据,第二个是fp 写入到文件的内容。
indent = 4 是设置缩进为4个空格

生成的yaml 文件如下

python 数据写入yaml 文件中文和排序问题_YAML

解决中文问题

查看 safe_dump 源码

def safe_dump(data, stream=None, **kwds):
"""
Serialize a Python object into a YAML stream.
Produce only basic YAML tags.
If stream is None, return the produced string instead.
"""
return dump_all([data], stream, Dumper=SafeDumper, **kwds)

调用的 dump_all 方法

def dump_all(documents, stream=None, Dumper=Dumper,
default_style=None, default_flow_style=False,
canonical=None, indent=None, width=None,
allow_unicode=None, line_break=None,
encoding=None, explicit_start=None, explicit_end=None,
version=None, tags=None, sort_keys=True):
"""
Serialize a sequence of Python objects into a YAML stream.
If stream is None, return the produced string instead.
"""

​allow_unicode​​​ 设置为 ​​True​​ 即可解决中文的问题

# 作者 上海-悠悠 

# 写入yaml 文件
with open("data.yml", 'w', encoding="utf-8") as fp:
yaml.safe_dump(data, fp, indent=4,
encoding='utf-8',
allow_unicode=True,
)

运行后生成的yaml结构

get请求:
name: GET请求示例
request:
method: GET
url: /get
sleep: 3

排序问题

python的字典是有序的,生成yaml 后发现key 是按a-z 的顺序排列,并不是python里面定义的字典的顺序

加上 ​​sort_keys=Flase​​ 可以解决排序问题

# 写入yaml 文件
with open("data.yml", 'w', encoding="utf-8") as fp:
yaml.safe_dump(data, fp, indent=4,
# default_flow_style=False,
encoding='utf-8',
allow_unicode=True,
sort_keys=False
)

运行后

get请求:
name: GET请求示例
sleep: 3
request:
method: GET
url: /get

需注意的是 ​​sort_keys=False​​​ 在一些比较低的 PyYAML 库中并没有这个参数,升级到最新版就行了。
​​​default_flow_style=False​​ 是设置yaml格式的风格,默认为False就可以了,新版的PyYAML 已经默认为False 了。



举报

相关推荐

0 条评论