python对yaml文件字典数据增删改读操作

目录

1.读取操作

2.增加操作

3.删除操作

4.修改操作


in.yaml文件的初始内容如下,以下操作都是对初始内容进行操作

1.读取操作

import yaml
import os
#in.yaml文件与当前的文件在同一个目录下

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

'''
读取数据
'''
def get_dict():
    d = {}   #in.yaml文件里面存了字典
    f = open(yamlPath, 'r', encoding='utf-8')
    d = yaml.load(f.read(), Loader=yaml.FullLoader)
    f.close()
    return d
print(get_dict())

输出

 

2.增加操作

import yaml
import os
#in.yaml文件与当前的文件在同一个目录下

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

'''
读取数据
'''
def get_dict():
    d = {}   #in.yaml文件里面存了字典
    f = open(yamlPath, 'r', encoding='utf-8')
    d = yaml.load(f.read(), Loader=yaml.FullLoader)
    f.close()
    return d
'''
增加数据
'''
def add_dict(a,b):
    data = {a:b}
    file = open(yamlPath, 'a', encoding='utf-8')
    yaml.dump(data, file)
    file.close()
add_dict('a','666')
print(get_dict())

输出

  

3.删除操作

import yaml
import os
#in.yaml文件与当前的文件在同一个目录下

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

'''
读取数据
'''
def get_dict():
    d = {}   #in.yaml文件里面存了字典
    f = open(yamlPath, 'r', encoding='utf-8')
    d = yaml.load(f.read(), Loader=yaml.FullLoader)
    f.close()
    return d
'''
删除操作
'''
def delete_data(data):
    d = {}
    with open('in.yaml','r+') as f:
        dict_temp = yaml.load(f,Loader=yaml.FullLoader)
        print(dict_temp)
        print(type(dict_temp))
        dict_temp.pop(data)
    with open('in.yaml', 'w') as f:
        yaml.dump(dict_temp,f)   #将Python中的字典或者列表转化为yaml格式的数据
        f.close()
        return d
delete_data('b')
print(get_dict())

这里的删除实际上是将yaml文件内容读取出来,删除字典里面的数据再写入in.yaml文件中。输出

 

4.修改操作

import yaml
import os
#in.yaml文件与当前的文件在同一个目录下

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

'''
读取数据
'''
def get_dict():
    d = {}   #in.yaml文件里面存了字典
    f = open(yamlPath, 'r', encoding='utf-8')
    d = yaml.load(f.read(), Loader=yaml.FullLoader)
    f.close()
    return d
'''
修改操作
'''
def change_data(key,data):

    with open('in.yaml') as f:
        dict_temp = yaml.load(f,Loader=yaml.FullLoader)
        dict_temp[key] = data
    with open('in.yaml', 'w') as f:
        yaml.dump(dict_temp,f)    #将Python中的字典或者列表转化为yaml格式的数据
        f.close()
change_data('b','D')
print(get_dict())

输出

 

 感觉需要了解更多的可以去下面的网址去查看自己需要的信息

pyyaml官方教程

  • 9
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夸父号

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值