我正在尝试将 yaml 文件转换为特定格式。YAML 文件如下所示:
treeroot:
branch1:
name: 1
branch1-1:
name: 2
branch2:
name: 3
branch2-1:
name: 4
我想将上述文件作为输入并以下列格式打印输出:
system.treeroot.branch1.name 1
system.treeroot.branch1.branch1-1.name 2
system.treeroot.branch2.name 3
system.treeroot.branch2.branch2-1.name 4
这是我编写的代码:
#!/usr/bin/python
import yaml
m = "system"
def main():
yaml_data = yaml.load(open('test.yaml'))
recurse(yaml_data)
def recurse(yaml_data):
for k,v in yaml_data.iteritems():
global m
if type(v) == type({}):
m = m + "." + k
recurse(v)
else:
m = m + "." + k
print str(m)+" "+str(v)
if __name__ == "__main__":
main()
但是这段代码打印的输出是这样的:
system.treeroot.branch2.branch2-1.name 4
system.treeroot.branch2.branch2-1.name.name 3
system.treeroot.branch2.branch2-1.name.name.branch1.branch1-1.name 2
system.treeroot.branch2.branch2-1.name.name.branch1.branch1-1.name.name 1
我该如何解决这个问题?