Python實現yaml與json文件批量互轉

目錄

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 yamlimport 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 yamlimport 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 yamlimport jsonimport osfrom pathlib import Pathfrom fnmatch import fnmatchcaseclass 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)

到此這篇關于Python實現yaml與json文件批量互轉得內容就介紹到這了,更多相關Python yaml json互轉內容請搜索之家以前得內容或繼續瀏覽下面得相關內容希望大家以后多多支持之家!

聲明:所有內容來自互聯網搜索結果,不保證100%準確性,僅供參考。如若本站內容侵犯了原著者的合法權益,可聯系我們進行處理。
發表評論
更多 網友評論1 條評論)
暫無評論

返回頂部

主站蜘蛛池模板: 亚洲精品字幕在线观看| 国产精品福利自产拍在线观看| 国产一级理仑片日本| 久久精品国产99国产精品亚洲| 免费观看国产网址你懂的| 欧美一区二区三区精品影视| 国产精品免费视频一区| 亚洲国产综合精品| 手机在线观看视频你懂的| 欧美乱妇狂野欧美在线视频| 国产精品三级电影在线观看| 亚洲人成激情在线播放| 亚洲AV无码成人专区| 777精品视频| 最近2018中文字幕2019国语视频| 国产激情视频一区二区三区| 亚洲AV无码专区在线播放| 黄视频免费下载| 日本www在线播放| 四虎网站1515hh四虎| 三级在线看中文字幕完整版| 精品免费国产一区二区三区| 女人张开腿让男人桶个爽| 伊人久久大香线蕉亚洲五月天 | 国产免费丝袜调教视频| 久久久国产视频| 综合久久久久久久综合网| 好吊妞视频一区二区| 亚洲精品中文字幕乱码| 男女一进一出抽搐免费视频| 日韩欧美在线播放| 国产69久久精品成人看| www.嫩草影院| 武则天一边上朝一边做h| 国产精品99在线观看| 久久精品久久精品| 美国发布站精品视频| 夜天干天干啦天干天天爽| 亚洲国产精品成人综合久久久| 黄色一级毛片在线观看| 护士撩起裙子让你桶的视频|