最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python實(shí)現(xiàn)yaml與json文件批量互轉(zhuǎn)

 更新時(shí)間:2022年07月27日 17:06:10   作者:將沖破艾迪i  
這篇文章主要為大家詳細(xì)介紹了如何利用Python語言實(shí)現(xiàn)yaml與json文件的批量互轉(zhuǎn),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以動手嘗試一下

1. 安裝yaml庫

想要使用python實(shí)現(xiàn)yaml與json格式互相轉(zhuǎn)換,需要先下載pip,再通過pip安裝yaml庫。

如何下載以及使用pip,可參考:pip的安裝與使用,解決pip下載速度慢的問題

安裝yaml庫:

pip install pyyaml

2. yaml轉(zhuǎn)json

新建一個(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"
          }
     }
}

3. json轉(zhuǎn)yaml

新建一個(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

4. 批量將yaml與json文件互相轉(zhuǎn)換

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)的文章就介紹到這了,更多相關(guān)Python yaml json互轉(zhuǎn)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python的二維數(shù)組初始化方式

    Python的二維數(shù)組初始化方式

    這篇文章主要介紹了Python的二維數(shù)組初始化方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-08-08
  • 使用plt.bar柱狀圖減小柱子之間的間隔問題

    使用plt.bar柱狀圖減小柱子之間的間隔問題

    這篇文章主要介紹了使用plt.bar柱狀圖減小柱子之間的間隔問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • Python排序算法快速排序VS歸并排序深入對比分析

    Python排序算法快速排序VS歸并排序深入對比分析

    快速排序和歸并排序是兩種常見的排序算法,在Python中有著重要的應(yīng)用,本文將深入探討這兩種算法的原理和實(shí)現(xiàn),并提供豐富的示例代碼來說明它們的工作方式
    2024-01-01
  • 使用Python?http.server模塊共享文件的方法詳解

    使用Python?http.server模塊共享文件的方法詳解

    大家好,今天給大家介紹一下Python標(biāo)準(zhǔn)庫中的http.server模塊,這個(gè)模塊提供了一種簡單的方式來快速啟動一個(gè)HTTP服務(wù)器,文中給大家介紹了使用Python?http.server模塊共享文件的方法,需要的朋友可以參考下
    2024-05-05
  • 如何使用 Pylint 來規(guī)范 Python 代碼風(fēng)格(來自IBM)

    如何使用 Pylint 來規(guī)范 Python 代碼風(fēng)格(來自IBM)

    本文通過詳細(xì)的理論介紹和簡單易懂的實(shí)例全面介紹了 Python 代碼分析工具 Pylint。相信讀者看完后一定可以輕松地將 Pylint 運(yùn)用到自己的開發(fā)工程中
    2018-04-04
  • Python 多線程超詳細(xì)到位總結(jié)

    Python 多線程超詳細(xì)到位總結(jié)

    線程在程序中是獨(dú)立的、并發(fā)的執(zhí)行流。與分隔的進(jìn)程相比,進(jìn)程中線程之間的隔離程度要小,它們共享內(nèi)存、文件句柄和其他進(jìn)程應(yīng)有的狀態(tài)。線程的劃分尺度小于進(jìn)程,使多線程程序的并發(fā)性高。進(jìn)程在執(zhí)行過程中擁有獨(dú)立內(nèi)存單元,而多個(gè)線程共享內(nèi)存,從而提升程序運(yùn)行效率
    2021-11-11
  • 在Python的Flask框架中使用日期和時(shí)間的教程

    在Python的Flask框架中使用日期和時(shí)間的教程

    這篇文章主要介紹了在Python的Flask框架中使用日期和時(shí)間的教程,包括對各個(gè)時(shí)區(qū)之間轉(zhuǎn)換的一些處理,需要的朋友可以參考下
    2015-04-04
  • Python線性表種的單鏈表詳解

    Python線性表種的單鏈表詳解

    這篇文章主要介紹了Python線性表種的單鏈表詳解,線性表是一種線性結(jié)構(gòu),它是由零個(gè)或多個(gè)數(shù)據(jù)元素構(gòu)成的有限序列。線性表的特征是在一個(gè)序列中,除了頭尾元素,每個(gè)元素都有且只有一個(gè)直接前驅(qū),有且只有一個(gè)直接后繼
    2022-08-08
  • Python生成MD5值的兩種方法實(shí)例分析

    Python生成MD5值的兩種方法實(shí)例分析

    這篇文章主要介紹了Python生成MD5值的兩種方法,結(jié)合實(shí)例形式較為詳細(xì)的分析了Python實(shí)現(xiàn)MD5加密的常見操作技巧,需要的朋友可以參考下
    2019-04-04
  • Python CSV模塊使用實(shí)例

    Python CSV模塊使用實(shí)例

    這篇文章主要介紹了Python CSV模塊使用實(shí)例,本文將舉幾個(gè)例子來介紹一下Python的CSV模塊的使用方法,包括reader、writer、DictReader、DictWriter.register_dialect等,需要的朋友可以參考下
    2015-04-04

最新評論

凉山| 共和县| 汶上县| 泰和县| 拉孜县| 石家庄市| 翁源县| 新化县| 班戈县| 卢龙县| 阿瓦提县| 景德镇市| 奇台县| 景洪市| 广安市| 孝感市| 昭平县| 福鼎市| 彩票| 贵州省| 上饶市| 湘西| 黎平县| 咸宁市| 唐山市| 陆河县| 迁安市| 沂南县| 固阳县| 六盘水市| 鲁山县| 屏边| 理塘县| 兰溪市| 乌苏市| 垦利县| 天水市| 崇明县| 平远县| 贺州市| 吉林省|