您好,登錄后才能下訂單哦!
這篇文章主要介紹“Python如何實(shí)現(xiàn)yaml與json文件批量互轉(zhuǎn)”,在日常操作中,相信很多人在Python如何實(shí)現(xiàn)yaml與json文件批量互轉(zhuǎn)問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”Python如何實(shí)現(xiàn)yaml與json文件批量互轉(zhuǎn)”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!
想要使用python實(shí)現(xiàn)yaml與json格式互相轉(zhuǎn)換,需要先下載pip,再通過pip安裝yaml庫。
如何下載以及使用pip,可參考:pip的安裝與使用,解決pip下載速度慢的問題
安裝yaml庫:
pip install pyyaml
新建一個(gè)test.yaml文件,添加以下內(nèi)容:
A: hello: name: Michael address: Beijing B: hello: name: jack address: Shanghai
代碼如下:
import yaml import json # yaml文件內(nèi)容轉(zhuǎn)換成json格式 def yaml_to_json(yamlPath): with open(yamlPath, encoding="utf-8") as f: datas = yaml.load(f,Loader=yaml.FullLoader) # 將文件的內(nèi)容轉(zhuǎn)換為字典形式 jsonDatas = json.dumps(datas, indent=5) # 將字典的內(nèi)容轉(zhuǎn)換為json格式的字符串 print(jsonDatas) if __name__ == "__main__": jsonPath = 'E:/Code/Python/test/test.yaml' yaml_to_json(jsonPath)
執(zhí)行結(jié)果如下:
{
"A": {
"hello": {
"name": "Michael",
"address": "Beijing"
}
},
"B": {
"hello": {
"name": "jack",
"address": "Shanghai"
}
}
}
新建一個(gè)test.json文件,添加以下內(nèi)容:
{ "A": { "hello": { "name": "Michael", "address": "Beijing" } }, "B": { "hello": { "name": "jack", "address": "Shanghai" } } }
代碼如下:
import yaml import json # json文件內(nèi)容轉(zhuǎn)換成yaml格式 def json_to_yaml(jsonPath): with open(jsonPath, encoding="utf-8") as f: datas = json.load(f) # 將文件的內(nèi)容轉(zhuǎn)換為字典形式 yamlDatas = yaml.dump(datas, indent=5, sort_keys=False) # 將字典的內(nèi)容轉(zhuǎn)換為yaml格式的字符串 print(yamlDatas) if __name__ == "__main__": jsonPath = 'E:/Code/Python/test/test.json' json_to_yaml(jsonPath)
執(zhí)行結(jié)果如下:
A:
hello:
name: Michael
address: Beijing
B:
hello:
name: jack
address: Shanghai
注意,如果不加sort_keys=False,那么默認(rèn)是排序的,則執(zhí)行結(jié)果如下:
A:
hello:
address: Beijing
name: Michael
B:
hello:
address: Shanghai
name: jack
yaml與json文件互相轉(zhuǎn)換:
import yaml import json import os from pathlib import Path from fnmatch import fnmatchcase class Yaml_Interconversion_Json: def __init__(self): self.filePathList = [] # yaml文件內(nèi)容轉(zhuǎn)換成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文件內(nèi)容轉(zhuǎn)換成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文件轉(zhuǎn)換成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文件轉(zhuǎn)換成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)
到此,關(guān)于“Python如何實(shí)現(xiàn)yaml與json文件批量互轉(zhuǎn)”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。