欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

1. 安裝yaml庫(kù)

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

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

安裝yaml庫(kù):

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文件同級(jí)目錄下,生成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文件同級(jí)目錄下,生成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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 用python批量移動(dòng)文件

    用python批量移動(dòng)文件

    這篇文章主要介紹了如何用python批量移動(dòng)文件,幫助大家更好的理解和使用python,感興趣的朋友可以了解下
    2021-01-01
  • Python繪圖之桃花盛開(kāi)

    Python繪圖之桃花盛開(kāi)

    這篇文章主要介紹了如何用python繪制桃花樹(shù),幫助大家更好的使用python處理圖片,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-08-08
  • Python中將列表轉(zhuǎn)化為鏈表的方法詳解

    Python中將列表轉(zhuǎn)化為鏈表的方法詳解

    這篇文章主要介紹了Python中將列表轉(zhuǎn)化為鏈表的方法詳解,本文的主要問(wèn)題是輸入一組數(shù),將其按照順序添加到鏈表中,文中提供了解決思路與部分實(shí)現(xiàn)代碼,需要的朋友可以參考下
    2023-11-11
  • Python3之外部文件調(diào)用Django程序操作model等文件實(shí)現(xiàn)方式

    Python3之外部文件調(diào)用Django程序操作model等文件實(shí)現(xiàn)方式

    這篇文章主要介紹了Python3之外部文件調(diào)用Django程序操作model等文件實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-04-04
  • openCV實(shí)現(xiàn)圖像融合的示例代碼

    openCV實(shí)現(xiàn)圖像融合的示例代碼

    圖像融合是兩幅圖片疊加在一起,本文主要介紹了openCV實(shí)現(xiàn)圖像融合的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • 利用python將?Matplotlib?可視化插入到?Excel表格中

    利用python將?Matplotlib?可視化插入到?Excel表格中

    這篇文章主要介紹了利用python將?Matplotlib?可視化?插入到?Excel?表格中,通過(guò)使用xlwings模塊來(lái)控制Excel插入圖表,具體詳細(xì)需要的朋友可以參考下面文章內(nèi)容
    2022-06-06
  • Python Web框架之Django框架Model基礎(chǔ)詳解

    Python Web框架之Django框架Model基礎(chǔ)詳解

    這篇文章主要介紹了Python Web框架之Django框架Model基礎(chǔ),結(jié)合實(shí)例形式分析了Django框架Model模型相關(guān)使用技巧與操作注意事項(xiàng),需要的朋友可以參考下
    2019-08-08
  • python字符串加密解密的三種方法分享(base64 win32com)

    python字符串加密解密的三種方法分享(base64 win32com)

    這篇文章主要介紹了python字符串加密解密的三種方法,包括用base64、使用win32com.client、自己寫(xiě)的加密解密算法三種方法,大家參考使用吧
    2014-01-01
  • Python圖片批量自動(dòng)摳圖去背景的代碼詳解

    Python圖片批量自動(dòng)摳圖去背景的代碼詳解

    這篇文章主要介紹了Python圖片批量自動(dòng)摳圖去背景,只要上傳圖片,就可以自動(dòng)把背景去掉把目標(biāo)對(duì)象摳出來(lái),非常方便,對(duì)Python圖片批量自動(dòng)摳圖去背景的代碼感興趣的朋友一起看看吧
    2022-03-03
  • pandas如何靈活增加新的空字段

    pandas如何靈活增加新的空字段

    這篇文章主要介紹了pandas如何靈活增加新的空字段問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-08-08

最新評(píng)論