目录
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())
输出
感觉需要了解更多的可以去下面的网址去查看自己需要的信息