22

python读取yaml配置文件

 3 years ago
source link: https://studygolang.com/articles/31064
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

什么是yaml

1、yaml [ˈjæməl]: Yet Another Markup Language :另一种标记语言。yaml 是专门用来写配置文件的语言,非常简洁和强大,

2、支持多种语言:python、js、golang、java、c、c++

3、yaml语法

  • 大小写敏感
  • 使用缩进表示层级关系
  • 缩进时不允许使用Tab键,只允许使用空格。
  • 缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
  • #号表示注释

4、yaml支持的数据结构有三种:

  • 对象:键值对的集合,又称为映射(mapping)/ 哈希(hashes) / 字典(dictionary)

  • 数组:一组按次序排列的值,又称为序列(sequence) / 列表(list)

  • 纯量(scalars):单个的、不可再分的值。字符串、布尔值、整数、浮点数、Null、时间、日期

在实际工作中,我们经常使用yaml文件来存储数据或者存储一些必要的配置,那么在python中,我们如何将存储在yaml文件中的数据转化为python可以识别的数据类型呢?

安装yaml

使用pip安装pyyaml模块

pip install pyyaml

python读取yaml案例

用python读取yaml文件案例如下,先用open方法读取文件数据,再通过load方法转成字典,这个load跟json里面的load是相似的。

# coding:utf-8
import yaml
import os

# 获取当前脚本所在文件夹路径
curPath = os.path.dirname(os.path.realpath(__file__))
# 获取yaml文件路径
yamlPath = os.path.join(curPath, "configyaml.yaml")

# open方法打开直接读出来
with open(yamlPath, 'r', encoding='utf-8') as f:
    config = f.read()
print(type(config))  # 读出来是字符串
print(config)

d = yaml.load(config,Loader=yaml.FullLoader)  # 用load方法转字典
print(d)
print(d.get('time1'))
print(type(d))

yaml写法及与python对应关系

1、键值对(dict)

字典写法

# yaml
user: admin
psw: 123456

嵌套字典写法

# yaml
user1:
    user: admin
    psw: 123456

2、序列(list)

yaml里面写一个数组,前面加一个‘-’符号,如下

#yaml
- admin1: 111111
- admin2: 222222
- admin3: 333333

对应python的列表嵌套字典

[{'admin1': 111111},
{'admin2': 222222}, 
{'admin3': 333333}]

3、纯量(str)

1.int和float类型的数字

n1: 12.30

2.布尔值用true和false表示

n2: true 
n3: false

3.None用~表示

n4: ~

4.时间采用 ISO8601 格式。

time1: 2001-12-14t21:59:43.10-05:00

对应python

{'time1': datetime.datetime(2001, 12, 15, 2, 59, 43, 100000)}

5.日期采用复合 iso8601 格式的年、月、日表示。

date1: 2017-07-31

对应python

{'date1': datetime.date(2017, 7, 31)}

6.使用两个感叹号,强制转换数据类型。

int转str

n6: !!str 123

对应python

{'n6': '123'}

bool值转str

n7: !!str true

对应python

{'n7': 'true'}

7.在yaml文件写入以下内容:

n1: 12.30
n2: true
n3: false
n4: ~
time1: 2018-04-18t21:59:43.10+08:00
date1: 2018-04-18
n6: !!str 123
n7: !!str true

python读取结果:

{'n1': 12.3, 
'n2': True, 
'n3': False, 
'n4': None, 
'time1': datetime.datetime(2018, 4, 18, 21, 59, 43, 100000, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800)))
'date1': datetime.date(2018, 4, 18), 
'n6': '123', 
'n7': 'true'}

4、混合使用

1.list嵌套dict,在yaml里面写入如下内容:

- user: admin1
  psw: '123456'

- user: admin2
  psw: '111111'

- user: admin3
  psw: '222222'

用python读取出来的结果:

[{'user': 'admin1', 'psw': '123456'},{'user': 'admin2', 'psw': '111111'},{'user': 'admin3', 'psw': '222222'}]

2.dict嵌套list,在yaml里面写入如下内容:

nub1:
    - admin1
    - '123456'

nb2:
    - admin2
    - '111111'

nb3:
    - admin3
    - '222222'

用python读取出来的结果:

{'nub1': ['admin1', '123456'], 'nb2': ['admin2', '111111'], 'nb3': ['admin3', '222222']}

有疑问加站长微信联系

iiUfA3j.png!mobile

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK