YAML文件读取和写入

YAML文件读取和写入

前言

yaml文件是什么?yaml文件其实也是一种配置文件类型,相比较ini,conf,py配置文件来说,更加的简洁,操作也更加简单,同时可以存放不同类型的数据,不会改变原有数据类型,所有的数据类型在读取时都会原样输出,yaml文件依赖python的第三方库PyYaml模块,pip install PyYaml

读取yaml

1.读取字典

1.1单组数据

config.yaml

logger:
  name: python25
  level: WARNING
  description: 12
excel:
  file: ~
  sheet: null

yaml_read.py

import yaml
def read_yaml():
    with open("config.yaml", encoding='utf-8') as f:
        data = yaml.load(f.read(), Loader=yaml.FullLoader)
        print(data)
        print(data["logger"]["name"])
read_yaml()

输出

{'logger': {'name': 'python25', 'level': 'WARNING', 'description': 12}, 'excel': {'file': None, 'sheet': None}}
python25

1.2多组字典数据读取

config.yaml
logger:
  name: python25
  level: WARNING
  description: 12
excel:
  file: ~
  sheet: null
---
student:
  name: lihua
  age: 12

yaml_read.py

import yaml
def read_yaml():
    with open("config.yaml", encoding='utf-8') as f:
        data = yaml.load_all(f.read(), Loader=yaml.FullLoader)
        print(data)
        for i in data:
            print(i)

read_yaml()

输出:

<generator object load_all at 0x0000024FA91894C0>
{'logger': {'name': 'python25', 'level': 'WARNING', 'description': 12}, 'excel': {'file': None, 'sheet': None}}
{'student': {'name': 'lihua', 'age': 12}}

通过输出结果及yaml存储内容可以看出,当yaml文件存储多组数据在一个yaml文件中时,需要使用3个横杆分割,读取数据时需要使用load_all方法,而且此方法返回一个生成器,需要使用for循环迭代读取每一组数据下面再看一下yaml如何存储列表类型数据

2 读取列表

config.yaml

- name
- age
- class

yaml_read.py

import yaml
def read_yaml():
    with open("config.yaml", encoding='utf-8') as f:
        data = yaml.load(f.read(), Loader=yaml.FullLoader)
        print(data)

read_yaml()

输出

['name', 'age', 'class']

3读取元祖

config.yaml

--- !!python/tuple # 列表转成元组
- name
- age
- class
---
age: !!str 18 # int 类型转换为str

read_yaml.py

import yaml
def read_yaml():
    with open("config.yaml", encoding='utf-8') as f:
        data = yaml.load_all(f.read(), Loader=yaml.FullLoader)
        print(data)
        for i in data:
            print(i)

read_yaml()

输出

<generator object load_all at 0x000001DD08D694C0>
['name', 'age', 'class']
{'age': '18'}

4 写入yaml文件

4.1 写入单组数据

response = {
    "status": 1,
    "code": "1001",
    "data": [
        {
            "id": 80,
            "regname": "toml",
            "pwd": "QW&@JBK!#&#($*@HLNN",
            "mobilephone": "13691579846",
            "leavemount": "0.00",
            "type": "1",
            "regtime": "2019-08-14 20:24:45.0"
        },
        {
            "id": 81,
            "regname": "toml",
            "pwd": "QW&@JBK!#&#($*@HLNN",
            "mobilephone": "13691579846",
            "leavemount": "0.00",
            "type": "1",
            "regtime": "2019-08-14 20:24:45.0"
        }
    ],
    "msg": "获取用户列表成功"
}

import yaml
def write_yaml():
    with open("config.yaml", encoding='utf-8',mode='w') as f:
        try:
            yaml.dump(data=response,stream=f,allow_unicode=True)
        except Exception as e:
            print(e)

write_yaml()

写入后的文件config.yaml为
c

ode: '1001'
data:
- id: 80
  leavemount: '0.00'
  mobilephone: '13691579846'
  pwd: QW&@JBK!#&#($*@HLNN
  regname: toml
  regtime: '2019-08-14 20:24:45.0'
  type: '1'
- id: 81
  leavemount: '0.00'
  mobilephone: '13691579846'
  pwd: QW&@JBK!#&#($*@HLNN
  regname: toml
  regtime: '2019-08-14 20:24:45.0'
  type: '1'
msg: 获取用户列表成功
status: 1

4.2写入多组数据

response = {
    "status": 1,
    "code": "1001",
    "data": [
        {
            "id": 80,
            "regname": "toml",
            "pwd": "QW&@JBK!#&#($*@HLNN",
            "mobilephone": "13691579846",
            "leavemount": "0.00",
            "type": "1",
            "regtime": "2019-08-14 20:24:45.0"
        },
        {
            "id": 81,
            "regname": "toml",
            "pwd": "QW&@JBK!#&#($*@HLNN",
            "mobilephone": "13691579846",
            "leavemount": "0.00",
            "type": "1",
            "regtime": "2019-08-14 20:24:45.0"
        }
    ],
    "msg": "获取用户列表成功"
}

info = {
    "name": "linux超",
    "age": 18
}
import yaml
def write_yaml():
    with open("config.yaml", encoding='utf-8',mode='w') as f:
        try:
            yaml.dump_all(documents=[response,info],stream=f,allow_unicode=True)
        except Exception as e:
            print(e)

write_yaml()
写入后的config.yaml为
code: '1001'
data:
- id: 80
  leavemount: '0.00'
  mobilephone: '13691579846'
  pwd: QW&@JBK!#&#($*@HLNN
  regname: toml
  regtime: '2019-08-14 20:24:45.0'
  type: '1'
- id: 81
  leavemount: '0.00'
  mobilephone: '13691579846'
  pwd: QW&@JBK!#&#($*@HLNN
  regname: toml
  regtime: '2019-08-14 20:24:45.0'
  type: '1'
msg: 获取用户列表成功
status: 1
---
age: 18
name: linux超

出处: 博客园Linux超的技术博客–https://www.cnblogs.com/linuxchao/
作者: Linux超



你可能感兴趣的:(python,python)