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__":
yamlPath = 'E:/Code/Python/test/test.yaml'
yaml_to_json(yamlPath)
执行结果如下:
{
"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_Interconversion_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, sort_keys=False)
# 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 = 'E:/Code/Python/test'
yaml_interconversion_json = Yaml_Interconversion_Json()
yaml_interconversion_json.batch_yaml_to_json(dirPath)
二、Yaml_Interconversion_Json类中函数的介绍:
yaml_to_json()
:把yaml文件内容转换成json格式,并返回json格式数据json_to_yaml()
:把json文件内容转换成yaml格式,并返回yaml格式数据generate_json_file()
:原yaml文件同级目录下,生成json文件generate_yaml_file()
:原json文件同级目录下,生成yaml文件batch_yaml_to_json()
:批量将目录下的yaml文件转换成json文件batch_json_to_yaml()
:批量将目录下的json文件转换成yaml文件batch_remove_file()
: 批量删除指定文件夹下所有相同名称的文件batch_remove_file_suffix()
:批量删除指定文件夹下所有相同后缀名的文件
三、函数用法如下:
准备工作:E:/Code/Python/test
目录下,准备以下文件及文件夹
- a文件夹:
- a.yaml
- test.yaml
- exception.yaml:异常格式的yaml文件
- test.yaml
a.yaml
和test.yaml
的内容同上,exception.yaml
的内容如下:
A:
hello
address: Beijing
name: Michael
B:
hello:
address: Shanghai
name: jack
示例一:传入yaml文件路径,在同级目录下生成json文件
代码:
filePath = 'E:/Code/Python/test/test.yaml'
yaml_interconversion_json = Yaml_Interconversion_Json()
yaml_interconversion_json.generate_json_file(filePath)
执行结果如下:
运行结果:
1.在test.yaml
的同级目录下,生成test.json
示例二:传入文件夹路径,批量将该文件夹下的yaml文件转换成json文件
代码:
dirPath = 'E:/Code/Python/test'
yaml_interconversion_json = Yaml_Interconversion_Json()
yaml_interconversion_json.batch_yaml_to_json(dirPath)
执行结果如下:
The converted yaml file is as follows:['E:/Code/Python/test/a/a.yaml', 'E:/Code/Python/test/a/test.yaml', 'E:/Code/Python/test/exception.yaml', 'E:/Code/Python/test/test.yaml']
YAML parsing error:mapping values are not allowed here
in "E:/Code/Python/test/exception.yaml", line 3, column 18
运行结果:
1.打印了批量转换文件的路径信息
2.打印了异常文件的信息
3.除了异常的exception.yaml
文件未能成功转换并生成json文件,其余的yaml文件都生成了对应的json文件
示例三:传入文件夹路径,批量删除指定文件夹下所有相同名称的文件
代码:
dirPath = 'E:/Code/Python/test'
fileName = 'test.yaml'
yaml_interconversion_json = Yaml_Interconversion_Json()
yaml_interconversion_json.batch_remove_file(dirPath, fileName)
执行结果如下:
The following files are deleted:['E:/Code/Python/test/a/test.yaml', 'E:/Code/Python/test/test.yaml']
运行结果:
1.打印了批量删除文件的路径信息
2.删除了test文件夹下所有test.yaml
文件
示例四:传入文件夹路径,批量删除指定文件夹下所有相同后缀名的文件
代码:
dirPath = 'E:/Code/Python/test'
suffix = 'yaml'
yaml_interconversion_json = Yaml_Interconversion_Json()
yaml_interconversion_json.batch_remove_file_suffix(dirPath, suffix)
执行结果如下:
The following files are deleted:['E:/Code/Python/test/a/a.yaml', 'E:/Code/Python/test/a/test.yaml', 'E:/Code/Python/test/exception.yaml', 'E:/Code/Python/test/test.yaml']
运行结果:
1.打印了批量删除文件的路径信息
2.删除了test文件夹下所有后缀名是.yaml
的文件