我需要爲YAML文件中的現有密鑰添加額外的值。以下是我正在使用的代碼。使用ruamel.yaml修改YAML會添加額外的新行
with open(yaml_in_path, 'r') as f:
doc, ind, bsi = load_yaml_guess_indent(f, preserve_quotes=True)
doc['phase1'] += ['c']
with open(yaml_out_path, 'w') as f:
ruamel.yaml.round_trip_dump(doc, f,
indent=2, block_seq_indent=bsi)
這是輸入和輸出。
輸入
phase1:
- a
# a comment.
- b
phase2:
- d
輸出
phase1:
- a
# a comment.
- b
- c
phase2:
- d
如何才能擺脫b
和c
之間的新生產線的? (當phase1
是文件中的唯一密鑰或phase1
和phase2
之間沒有空行時,此問題不存在)。
感謝您的支持。你能解釋一下在分配[x,None,None,None]而不是[x]後面的推理嗎?我在哪裏可以查看ruamel.yaml的源代碼以瞭解此數據結構? – keheliya
我不知道如果我在所有情況下都正確地檢查了它的長度,你可能會少一些,但我不會嘗試。這不是故意記錄的,因爲它可以在將來的版本中更改。 'ca'屬性是'ruamel.yaml.comments.Comment()'的一個實例,'x'是'ruamel.yaml.tokens.CommentToken()'。提示:如果沒有人問你,請使用'print(type(l.ca),'\ n',type(x))';-)。 – Anthon
嘿@安徒生,我剛剛偶然發現了這個同樣的問題。自發布此答案以來有任何更新的機會?現在可以用更優雅的方式避免這種情況了嗎?謝謝! – jakubka