【问题标题】:How to make this code to take multiple yaml input files and convert them to .json and save all of them to specified path如何使此代码获取多个 yaml 输入文件并将它们转换为 .json 并将它们全部保存到指定路径
【发布时间】:2021-11-25 13:52:41
【问题描述】:
def convert():             #function to convert .yaml to .json 

    in_file = filepath     #assigning input file from GUI to variable
    out_file = savepath    #assigning output path from GUI to variable 
    yaml = ruamel.yaml.YAML(typ='safe')
    with open(in_file ) as i:       #opening yaml file 
        data = yaml.load(i)
    with open(out_file, 'w') as o:  #writing json file
        json.dump(data, o, indent=2)

【问题讨论】:

    标签: python json yaml


    【解决方案1】:

    您的代码格式不正确。但是假设您的代码如下所示:

    def convert():
        in_file = filepath     #assigning input file from GUI to variable
        out_file = savepath    #assigning output path from GUI to variable 
        yaml = ruamel.yaml.YAML(typ='safe')
        with open(in_file ) as i:       #opening yaml file 
            data = yaml.load(i)
        with open(out_file, 'w') as o:  #writing json file
            json.dump(data, o, indent=2)
    

    你必须在这里改变一些逻辑:

    1. 您必须获取文件名s信息而不是文件名。它可以是可以从glob 获取的路径列表。然后您可以在文件中循环获取单个文件名。

    2. 由于您有多个文件,因此您无法提供 1 个文件名并以相同的名称保存所有文件。我能想到的最好的方法是(假设您正在将 yaml 文件转换为 json 文件)您可以替换文件的扩展名并使用相同的名称保存。

    获取文件名:

    glob 模块查找与指定模式匹配的所有路径名 根据 Unix shell 使用的规则,虽然结果是 以任意顺序返回。

    glob

    现在让我们使用它:

    from glob import glob
    files = glob("/your/path/*.yaml")
    
    for file in files:
        print(files)
    

    这里的文件是每个 yaml 文件的路径。现在您可以在循环中打开/使用该文件名并做任何您想做的事情。

    保存文件

    要将文件保存为 json,您可以:

    1. 在文件名中添加 .json

    基本上是用+或者fstrings来添加.json。

    json_file_name = file + ".json"
    

    json_file_name = f"{file}.json"
    

    请注意,您的文件名可能看起来很奇怪。因为您会将my_file.yaml 更改为my_file.yaml.json

    1. 用 json 替换 yaml

    由于文件路径是字符串,您可以使用replace 方法并替换文件名。

    json_file_name = file.replace("yaml", "json")
    

    这里你的文件名会更好看,但它会改变名称中的所有yamls。因此,如果您的文件名中包含 yaml,它也会被更改。

    喜欢my_yaml_file.yaml 更改为my_json_file.json

    【讨论】:

    • 如果需要更多说明,这是我的代码---github.com/saurabhkingp/school_management/blob/main/test.py
    • 好的,所以我使用 filedialog.askdirectory() 来获取从 GUI 到变量的路径,但是当我使用该变量像这样在 glob 内部传递时—— files = glob("filepath/* .yaml") for file in files: print(files) 它给了我错误 D_Lib: 文件 [.*] 和级别 [100] 的调试打印已打开 D_Lib: 文件 [.*] 和级别 [200] 的调试打印] 已打开 D_Lib:文件 [.*] 和级别 [300] 的调试打印已打开 20496:.../engine/vf_shex/vf_shex.cpp(91): INFO: DllCanUnloadNow 返回 S_OK。现在该怎么办?
    • 是的,这有帮助,我认为这只是一个警告
    • 现在当我使用 def open_file(): global filepath filepath=filedialog.askdirectory(title="Select a Directory") files = glob("filepath/*.yaml") for file in files : print(files)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 2020-06-06
    • 2015-03-04
    • 2022-12-10
    • 2020-06-27
    • 2020-02-20
    • 2022-12-10
    相关资源
    最近更新 更多