Python实现yaml与json文件批量互转
作者:将冲破艾迪i 发布时间:2023-11-20 07:07:54
1. 安装yaml库
想要使用python实现yaml与json格式互相转换,需要先下载pip,再通过pip安装yaml库。
如何下载以及使用pip,可参考:pip的安装与使用,解决pip下载速度慢的问题
安装yaml库:
pip install pyyaml
2. yaml转json
新建一个test.yaml文件,添加以下内容:
A:
hello:
name: Michael
address: Beijing
B:
hello:
name: jack
address: Shanghai
代码如下:
import yaml
import json
# yaml文件内容转换成json格式
def yaml_to_json(yamlPath):
with open(yamlPath, encoding="utf-8") as f:
datas = yaml.load(f,Loader=yaml.FullLoader) # 将文件的内容转换为字典形式
jsonDatas = json.dumps(datas, indent=5) # 将字典的内容转换为json格式的字符串
print(jsonDatas)
if __name__ == "__main__":
jsonPath = 'E:/Code/Python/test/test.yaml'
yaml_to_json(jsonPath)
执行结果如下:
{
"A": {
"hello": {
"name": "Michael",
"address": "Beijing"
}
},
"B": {
"hello": {
"name": "jack",
"address": "Shanghai"
}
}
}
3. json转yaml
新建一个test.json文件,添加以下内容:
{
"A": {
"hello": {
"name": "Michael",
"address": "Beijing"
}
},
"B": {
"hello": {
"name": "jack",
"address": "Shanghai"
}
}
}
代码如下:
import yaml
import json
# json文件内容转换成yaml格式
def json_to_yaml(jsonPath):
with open(jsonPath, encoding="utf-8") as f:
datas = json.load(f) # 将文件的内容转换为字典形式
yamlDatas = yaml.dump(datas, indent=5, sort_keys=False) # 将字典的内容转换为yaml格式的字符串
print(yamlDatas)
if __name__ == "__main__":
jsonPath = 'E:/Code/Python/test/test.json'
json_to_yaml(jsonPath)
执行结果如下:
A:
hello:
name: Michael
address: Beijing
B:
hello:
name: jack
address: Shanghai
注意,如果不加sort_keys=False,那么默认是排序的,则执行结果如下:
A:
hello:
address: Beijing
name: Michael
B:
hello:
address: Shanghai
name: jack
4. 批量将yaml与json文件互相转换
yaml与json文件互相转换:
import yaml
import json
import os
from pathlib import Path
from fnmatch import fnmatchcase
class Yaml_Interconversion_Json:
def __init__(self):
self.filePathList = []
# yaml文件内容转换成json格式
def yaml_to_json(self, yamlPath):
with open(yamlPath, encoding="utf-8") as f:
datas = yaml.load(f,Loader=yaml.FullLoader)
jsonDatas = json.dumps(datas, indent=5)
# print(jsonDatas)
return jsonDatas
# json文件内容转换成yaml格式
def json_to_yaml(self, jsonPath):
with open(jsonPath, encoding="utf-8") as f:
datas = json.load(f)
yamlDatas = yaml.dump(datas, indent=5)
# print(yamlDatas)
return yamlDatas
# 生成文件
def generate_file(self, filePath, datas):
if os.path.exists(filePath):
os.remove(filePath)
with open(filePath,'w') as f:
f.write(datas)
# 清空列表
def clear_list(self):
self.filePathList.clear()
# 修改文件后缀
def modify_file_suffix(self, filePath, suffix):
dirPath = os.path.dirname(filePath)
fileName = Path(filePath).stem + suffix
newPath = dirPath + '/' + fileName
# print('{}_path:{}'.format(suffix, newPath))
return newPath
# 原yaml文件同级目录下,生成json文件
def generate_json_file(self, yamlPath, suffix ='.json'):
jsonDatas = self.yaml_to_json(yamlPath)
jsonPath = self.modify_file_suffix(yamlPath, suffix)
# print('jsonPath:{}'.format(jsonPath))
self.generate_file(jsonPath, jsonDatas)
# 原json文件同级目录下,生成yaml文件
def generate_yaml_file(self, jsonPath, suffix ='.yaml'):
yamlDatas = self.json_to_yaml(jsonPath)
yamlPath = self.modify_file_suffix(jsonPath, suffix)
# print('yamlPath:{}'.format(yamlPath))
self.generate_file(yamlPath, yamlDatas)
# 查找指定文件夹下所有相同名称的文件
def search_file(self, dirPath, fileName):
dirs = os.listdir(dirPath)
for currentFile in dirs:
absPath = dirPath + '/' + currentFile
if os.path.isdir(absPath):
self.search_file(absPath, fileName)
elif currentFile == fileName:
self.filePathList.append(absPath)
# 查找指定文件夹下所有相同后缀名的文件
def search_file_suffix(self, dirPath, suffix):
dirs = os.listdir(dirPath)
for currentFile in dirs:
absPath = dirPath + '/' + currentFile
if os.path.isdir(absPath):
if fnmatchcase(currentFile,'.*'):
pass
else:
self.search_file_suffix(absPath, suffix)
elif currentFile.split('.')[-1] == suffix:
self.filePathList.append(absPath)
# 批量删除指定文件夹下所有相同名称的文件
def batch_remove_file(self, dirPath, fileName):
self.search_file(dirPath, fileName)
print('The following files are deleted:{}'.format(self.filePathList))
for filePath in self.filePathList:
if os.path.exists(filePath):
os.remove(filePath)
self.clear_list()
# 批量删除指定文件夹下所有相同后缀名的文件
def batch_remove_file_suffix(self, dirPath, suffix):
self.search_file_suffix(dirPath, suffix)
print('The following files are deleted:{}'.format(self.filePathList))
for filePath in self.filePathList:
if os.path.exists(filePath):
os.remove(filePath)
self.clear_list()
# 批量将目录下的yaml文件转换成json文件
def batch_yaml_to_json(self, dirPath):
self.search_file_suffix(dirPath, 'yaml')
print('The converted yaml file is as follows:{}'.format(self.filePathList))
for yamPath in self.filePathList:
try:
self.generate_json_file(yamPath)
except Exception as e:
print('YAML parsing error:{}'.format(e))
self.clear_list()
# 批量将目录下的json文件转换成yaml文件
def batch_json_to_yaml(self, dirPath):
self.search_file_suffix(dirPath, 'json')
print('The converted json file is as follows:{}'.format(self.filePathList))
for jsonPath in self.filePathList:
try:
self.generate_yaml_file(jsonPath)
except Exception as e:
print('JSON parsing error:{}'.format(jsonPath))
print(e)
self.clear_list()
if __name__ == "__main__":
dirPath = 'C:/Users/hwx1109527/Desktop/yaml_to_json'
fileName = 'os_deploy_config.yaml'
suffix = 'yaml'
filePath = dirPath + '/' + fileName
yaml_interconversion_json = Yaml_Interconversion_Json()
yaml_interconversion_json.batch_yaml_to_json(dirPath)
# yaml_interconversion_json.batch_json_to_yaml(dirPath)
# yaml_interconversion_json.batch_remove_file_suffix(dirPath, suffix)
来源:https://blog.csdn.net/aidijava/article/details/125630629


猜你喜欢
- 在tensorflow中,默认指定占用所有的GPU,如需指定占用的GPU,可以在命令行中:export CUDA_VISIBLE_DEVIC
- Infopath的使用避免了最终用户以完全手写的方式生成XML数据文件,同时也可以统一XML文件的格式,在MOSS系统和网站开发中被广泛使用
- 用pytorch训练一个神经网络时,我们通常会很关心模型的参数总量。下面分别介绍来两种方法求模型参数一 .求得每一层的模型参数,然后自然的可
- 本文实例讲述了微信小程序picker组件简单用法。分享给大家供大家参考,具体如下:picker滚动选择器,现支持三种选择器,通过mode来区
- 在开发的过程中,经常会遇到需要给别人提供一个输入框,然后别人输入一些ID,或者关键字的东西,例如wordpress的后台的标签输入框:这个就
- 本文实例讲述了Python + Requests + Unittest接口自动化测试。分享给大家供大家参考,具体如下:1. 介绍下pytho
- Golang 支持交叉编译,在一个平台上生成另一个平台的可执行程序,最近使用了一下,非常好用,这里备忘一下。Mac 下编译 Linux 和
- Javascript中的eval函数让我们可以很方便地操作一系列变量(a1,a2,a3,……)。自从VBScript 5.0之后,我们也可以
- 一、Jupyter Notebook是什么?1.notebook jupyter简介Jupyter Notebook是一个开源Web应用程序
- eval前言In [1]: eval("2+3")Out[1]: 5In [2]: eval('[x for x
- 本文实例讲述了js+css实现有立体感的按钮式文字竖排菜单效果。分享给大家供大家参考。具体如下:这是一款较不错的竖排菜单,有立体感效果的菜单
- MySQL使用环境变量TMPDIR的值作为保存临时文件的目录的路径名。如果未设置TMPDIR,MySQL将使用系统的默认值,通常为/tmp、
- 之前我们使用VSCode搭建C#项目,今天写一篇关于django项目的搭建,其实以其说是搭建django框架,不如说是如何通过vscode开
- 关于php的引用(就是在变量或者函数、对象等前面加上&符号)的作用,我们先看下面这个程序。<?php
- 1. 安装Opencv包pip install opvencv-python2.实现代码:视频转为图片:import cv2cap=cv2.
- 很多时候,我们需要对List进行排序,Python提供了两个方法,对给定的List L进行排序:方法1.用List的成员函数sort进行排序
- 通过一条命令用Npm安装gulp-htmlmin:npm install gulp-htmlmin --save-dev安装完毕后,打开gu
- 前言本篇文章分享一下我在实际开发小程序时遇到的需要获取用户当前位置的问题,在小程序开发过程中经常使用到的获取定位功能。uniapp官方也提供
- 回顾我们的python制作小游戏之路,几篇非常精彩的文章我们用python实现了坦克大战python制作坦克大战我们用python实现了飞船
- PYTHON是一门动态解释性的强类型定义语言:编写时无需定义变量类型;运行时变量类型强制固定;无需编译,在解释器环境直接运行。动态和静态静态