如何使此代码获取多个 yaml 输入文件并将它们转换为 .json 并将它们全部保存到指定路径

How to make this code to take multiple yaml input files and convert them to .json and save all of them to specified path

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)

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

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 文件)您可以替换文件的扩展名并用相同的名称保存它。

正在获取文件名:

The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell, although results are returned in arbitrary order.

glob

现在让我们使用它:

from glob import glob
files = glob("/your/path/*.yaml")

for file in files:
    print(files)

这里的文件是每个yaml文件的路径。现在你可以 open/use 循环中的那个文件名并做任何你想做的事。

正在保存文件

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

  1. 在文件名中添加.json

基本都是用+或者fstrings加.json.

json_file_name = file + ".json"

json_file_name = f"{file}.json"

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

  1. 将 yaml 替换为 json

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

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

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

my_yaml_file.yaml 改为 my_json_file.json.