python对yaml文件的处理

本文介绍如何使用Python的PyYAML库读取YAML格式的配置文件,并提供了一个具体的例子,展示了如何解析复杂的YAML数据结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

二、安装yaml

pip命令: pip install PyYaml
引入:import yaml
用python读取yaml文件如下:

代码:
import yaml
 

代码如下:

import yaml,os
# 打开yaml文件
caps_dir = 'C:\\Users\\Administrator\\Desktop'
fs = open(os.path.join(caps_dir, "yaml.yaml"),mode='r',encoding="UTF-8")
datas = yaml.load(fs,Loader=yaml.FullLoader)  #添加后就不警告了
print(datas["person"]["university"][0]["weight"])

准备的yaml文件如下:

%ymal 1.2
---
person:
  name: kmor
  age: 22
  sex: 男
  funny: 
    - a: football
    - b: basktball    
  address:
    provence: 湖北,
    city: 武汉,
    area: 江夏,
    street: 马房山街道办
  university:
    - A: grilA
      weight: 98
      height: 164
      age: 22
    - B: grilB
      weight: 96
      height: 162
      age: 21
  subject:
    main:electric
    sub:law
  comment1:
    aaaaaaa
    bbbbbbb
    ccccccc
  comment2: >
    ddddddd
    eeeeeee
    fffffff
  comment3: |
    ggggggg
    hhhhhhh
    iiiiiii
  mother: &mother_info
   age: 55
   name: jan
  woman: *mother_info
  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值