Python,仅更改一个字段即可生成相同 yaml 副本的有效方法?

Python, efficient way of generating copies the same yaml with only one field changed?

假设我得到一个名为“label.yaml”的 yaml 文件

id: 1
color: red
toy: car

我想制作此文件的 10000 个副本,id 是唯一会更改的值,它所要做的就是逐步更改。

id: 1
color: red
toy: car
id: 2
color: red
toy: car
id: 3
color: red
toy: car

... 等等...

我试过的东西:

import yaml

with open("data.yaml") as f:
    data = yaml.safe_load(f)


for i in range(1,100001):
    data["id"] = i

    with open(f"data-{i}.yaml", "w+") as f:
        yaml.dump(data, f)

有没有更有效的方法来做到这一点?

我可能会建议一个简单的技巧,而不是调用 yaml.dumpyaml.load,您可以只拥有一个包含 YAML 内容的字符串,进行字符串替换,然后将字符串内容写入文件直接,没有 yaml 库。

下面的示例使用 str.format 在每个循环迭代中使用局部变量 i 格式化模板字符串。

file_template = """
id: {}
color: red
toy: car
""".strip()

for i in range(1,100001):
    file_contents = file_template.format(i)

    with open(f"data-{i}.yaml", "w") as f:
        f.write(file_contents)

注意:根据 this discussion,不幸的是,似乎没有办法使用 open 来加速磁盘 IO。我觉得这可能是可能的最优化版本 - 请注意,您可能注意到的执行时间长主要是因为磁盘 I/O,它本质上很慢。