Python 对 yaml数据进行 读,写,添加数据操作 (read, wrire and add data in the yaml files using the python)

Python 对 yaml数据进行 读,写,添加数据操作

背景(background)

在做ROS项目的过程中,需要利用python首先从yaml 文件中读取数据作为函数的输入参数,然后利用这些参数进行计算,最后将计算结果添加并保存到这个yaml 文件的结尾(保留原来数据)(In the process of doing ROS projects, it has happed to me that using Python to first read data from the yaml file as input parameters of the function, then add and save the results of the function to the end of the yaml file (keeping the original data in the yaml files) )。

代码(codes)

# -*- coding: utf-8 -*-
# pip install PyYAML first !
import yaml
# read date
with open('config.yaml', 'r') as f:
    config_r = yaml.safe_load(f)

print(config_r['port'])

# add date in the end
data_msg = {"aa": 77,
     "bb":{"cc":66}
     }

with open("config.yaml", 'a', encoding="UTF8") as f:
    yaml.dump(data_msg, f)
    
# update data without saving the old data !
config = {

        'host': 'localhost',
        'port': 3306,
        'username': 'root',
        'password': 'password'

}

with open('config.yaml', 'w') as f:
    yaml.dump(config, f)

Note: do not forget install the package of pyyaml by " pip install PyYAML " first !

添加内容(Content addition)

实际操作的过程中,发现当添加的字典数据键值对里面的数据是numpy 数组的时候,保存结果总是不对,需要将键值对中的值变换成列表类型数据。(the the vale of numpy in the dict can not saved in the end of the yaml directory. we need to transfer the numpy date to the list date about the value of the dict.)另外一点就是,读完数据以后必须首先关闭yaml 文件,然后才能执行文件末尾添加数据的操作( by the way , after dealling the data of yaml, you had beter to close the yaml files and then do other operations)


# add date in the end of yaml files
            data_msg = {"S_B": KeyPathPointGPS[0][0].tolist(),
                        "S_L": KeyPathPointGPS[0][1].tolist(),
                        "D_B": KeyPathPointGPS[1][0].tolist(),
                        "D_L": KeyPathPointGPS[1][1].tolist(),
                        "E_B": KeyPathPointGPS[2][0].tolist(),
                        "E_L": KeyPathPointGPS[2][1].tolist()           
                        }
	    
            with open(PKG_PATH + "config/RANSAC_PathPlanning_transformation.yaml", 'a', encoding="UTF8") as f:
                yaml.dump(data_msg, f)



# open yaml
fr = open('文件路径','r')   
# other operations
# close the yaml
fr.close()

待续: 如何修改yaml文件中的数据(如果没有键值对进行添加,如果存在对键值对中的值进行修改)
(to do , how to edit the data of yaml files, if it exist, only modify the vale of the key-vale, if it does not exist add the key-vale)

https://blog.csdn.net/zhenzhendexiaoer/article/details/77833981
https://www.coder.work/article/2410055

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值