Python基础笔记2-ruamel.yaml读写yaml文件

上一篇笔记记录了Python中的pyyaml库对yaml文件进行读写,但了解到ruamel.yaml也能对yaml文件进行读写,于是想尝试一下它的用法。

一,注意

这里首先要更正一下网上大部分博客的说法:使用PyYAML写入时不是yaml的标准形式。例如使用PyYAML将字典嵌套字典的数据写入yaml文件时,写入的yaml文件里会出现带{}的数据。实际我在写代码的过程中发现PyYAML5.3.1版本并不会出现这种情况。如下所示:

使用PyYAML库写入yaml文件

# @author: 给你一页白纸

import yaml

data = {
   "str": "Hello world.",
   "int": 110,
   "list": [10, "she", ["he", "it"]],
   "dict": {"account":"xiaoqq", "password": {"pwd1": 123456, "pwd2": "water"}},
   "tuple": (100, "a")
}

with open('./writeYamlData.yml', 'w', encoding='utf-8') as f:
   yaml.dump(data=data, stream=f, allow_unicode=True)

写入后的yaml文件内容如下:

dict:
  account: xiaoqq
  password:
    pwd1: 123456
    pwd2: water
int: 110
list:
- 10
- she
- - he
  - it
str: Hello world.
tuple: !!python/tuple
- 100
- a

二,安装ruamel.yaml库

安装命令:

pip install ruamel.yaml
# 安装速度慢则加上镜像源
pip install ruamel.yaml -i https://pypi.tuna.tsinghua.edu.cn/simple

使用时导入:

from ruamel import yaml

三,ruamel.yaml写入yaml文件

使用yaml.dump()方法写入,代码展示如下:

# @author: 给你一页白纸

from ruamel import yaml

data = {
   "str": "Hello world.",
   "int": 110,
   "list": [10, "she", ["he", "it"]],
   "dict": {"account":"xiaoqq", "password": {"pwd1": 123456, "pwd2": "water"}},
   "tuple": (100, "a")
}

# path为yaml文件的绝对路径
path ='./writeYamlData.yml'

with open(path, 'w', encoding='utf-8') as f:
   yaml.dump(data, f, Dumper=yaml.RoundTripDumper)

写入结果如下:

str: Hello world.
int: 110
list:
- 10
- she
- - he
  - it
dict:
  account: xiaoqq
  password:
    pwd1: 123456
    pwd2: water
tuple:
- 100
- a

注意:这里yaml.dump()里加上l了参数Dumper=yaml.RoundTripDumper。不加该参数则写入结果如下:

dict:
  account: xiaoqq
  password: {pwd1: 123456, pwd2: water}
int: 110
list:
- 10
- she
- [he, it]
str: Hello world.
tuple: !!python/tuple [100, a]

四,ruamel.yaml读取yaml文件

yaml文件数据如下:

dict:
  account: xiaoqq
  password:
    pwd1: 123456
    pwd2: water
int: 110
list:
- 10
- she
- - he
  - it
str: Hello world.
tuple: !!python/tuple
- 100
- a

使用yaml.load()方法读取,代码展示如下:

# @author: 给你一页白纸

from ruamel import yaml

# path为yaml文件的绝对路径
path ='./writeYamlData.y'

with open(path, 'r', encoding='utf-8') as doc:
    content = yaml.load(doc, Loader=yaml.Loader)
    print(content)

读取结果如下:

C:\Users\xiaoqq\AppData\Local\Programs\Python\Python37\python.exe C:/Users/xiaoqq/Desktop/test_project/readYaml.py
{'dict': {'account': 'xiaoqq', 'password': {'pwd1': 123456, 'pwd2': 'water'}}, 'int': 110, 'list': [10, 'she', ['he', 'it']], 'str': 'Hello world.', 'tuple': (100, 'a')}


Process finished with exit code 0

ruamel.yaml库继承子PyMYAL库,读写方法基本相同,目前来说可以根据自己的习惯选择使用 ruamel.yaml 还是 PyMYAL 进行yaml文件的读写操作。

posted @ 2020-09-22 16:35  给你一页白纸  阅读(2125)  评论(0编辑  收藏  举报