【发布时间】:2021-06-21 14:24:48
【问题描述】:
我正在使用 PyYAML 库动态生成 YAML 文件。
例如,
import yaml
with open(r'content.txt', 'r') as a_file:
with open(r'file.yaml', 'a') as file:
file.write(" root:")
file.write("\n")
for line in a_file:
stripped_line = line.strip()
txt = stripped_line
x = txt.split("=")
with open(r'file.yaml', 'a') as file:
yaml.dump([{'child-1':x[0],'child-2':x[1]}])
content.txt 文件可能包含以下形式的数据:
a=b
c=d
所需的最终 YAML 文件应如下所示:
root:
- child-1: a
child-2: b
- child-1: c
child-2: d
请注意根对象的缩进,假设它嵌套在另一个根对象中
但是上面的代码使得输出为:
root:
- child-1: a
child-2: b
- child-1: c
child-2: d
这不是有效的 YAML。
在yaml.dump() 命令中提及根对象会重复它:
#for line in content.txt
#yaml.dump({'root':[{'child-1': x[0], 'child-2':x[1]}])
root:
- child-1: a
child-2: b
root
- child-1: c
child-2: d
由于pythonyaml.dump()函数要求我们将对象连同其子对象一起完整地提及,因此分开处理这2个对象似乎很困难。
有没有办法分开调用这些对象并稍后附加/链接根子对象?
【问题讨论】: