首页 > 编程语言 >python解析yaml文件

python解析yaml文件

时间:2022-12-03 10:00:11浏览次数:32  
标签:文件 python self yaml mode file path 解析

1、初始化yaml文件的目录

  def __init__(self):
self.yaml_root_path = 'D:\\Code\\PythonProject\\UIAutoProject\\config\\yaml\\'

2、读取yaml文件的方法

    def read_yaml(self, file_path):
"""
读取yaml文件内容
:param file_path: 文件路径
:return: 解析后的yaml文件数据
"""
with open(self.yaml_root_path + file_path, mode='r', encoding='utf-8') as f:
return yaml.load(stream=f, Loader=yaml.FullLoader)

运行结果

python解析yaml文件_ico

3、写入输入到yaml文件中

    def write_yaml(self, data, file_path, is_append):
"""
向yaml文件中写入数据
:param data: 需要写入的数据
:param file_path: 写入的文件路径
:param is_append: 数据是否追加到yaml文件
:return: 无
"""
# 数据样例 test_data = [dict(test=dict(username='王', password='654')), dict(test=dict(username='柯', password='321'))]
if is_append:
mode = 'a'
else:
mode = 'w'
with open(file=self.yaml_root_path + file_path, mode=mode) as f:
yaml.dump(data=data, stream=f, allow_unicode=True, sort_keys=False, default_flow_style=False)

4、清空yaml文件的内容

    def truncate_yaml(self, file_path):
"""
清空yaml文件内容
:param file_path:
:return: 无
"""
with open(file=self.yaml_root_path + file_path, mode='w') as f:
f.truncate()

标签:文件,python,self,yaml,mode,file,path,解析
From: https://blog.51cto.com/u_15694134/5908486

相关文章

  • Python遍历某个文件夹下的所有文件夹,每个文件夹只保留最新7个文件
    importosroot=r"D:\_back"fordirpath,dirnames,filenamesinos.walk(root):fordirnameindirnames:_dir=os.path.join(dirpath,dirname)......
  • Python实验报告——第13章 Pygame游戏编程
    实验报告实例01:制作一个跳跃的小球游戏代码如下:importsysimportpygamepygame.init()size=width,height=640,480screem=pygame.display.set_mode(size)c......
  • 解析式和生成器表达式
    列表解析式列表解析式ListComprehension,也叫列表推导式x=[]foriinrange(10):x.append((i+1)**2)print(x)写成推导式[(i+1)**2foriinrange(10)]Out[......
  • python 高阶函数
    高阶函数(High-orderFunction)​ 数学概念y=f(g(x))​ 在数学和计算机科学中,高阶函数应当是至少满足下面一个条件的函数​ 接受一个或多个函数作为参数​ 输......
  • python 装饰器
    defadd(x,y):returnx+ydeflogger(fn):defwrapper(*args,**kwargs):print('调用前增强')ret=fn(*args,**kwargs)#参数解构......
  • python 函数与生成器
    函数Python函数​ 由若干语句组成的语句块、函数名称、参数列表构成,它是组织代码的最小单元​ 完成一定的功能函数的作用​ 结构化编程对代码的最基本的封装,一般按......
  • python-练习(if for while语句)
    1.在终端中输入整数,打印正数,负数,零number=int(input("请输入整数"))ifnumber>0:print("正数")elifnumber<0:print("负数")else:print("零"......
  • Python 两个数字拼接
    问题:如何将两个数字拼接解决方法:将整形数字转成字符串拼接后,在转回整形。>>>a=1>>>b=2>>>c=str(a)+str(b)>>>print(int(c))12 ......
  • 第13章python实训
    实验报告实验目的1.了解和掌握Pygame的基础知识。【实验条件】1.PC机或者远程编程环境。 【实验内容】1.完成第十三章  实例01:篮球自动弹跳。 实例01:创建计......
  • PYTHON - openpyxl (二)
    1.1写数据语句说明工作表["a1"]=值写数据到一个单元格工作表.cell(行,列).value=值写数据到一个单元格工作表.cell(行,列,value=值)同上工作表.......