我有一个 yaml 文件,想更改同一个文件 temp.yaml
的几个参数。
%YAML 1.2
---
name: first
cmp:
- Some: first
top:
top_rate: 16000
audio_device: "pulse"
---
name: second
components:
- name: second
parameters:
always_on: true
timeout: 200000
我可以使用 yaml.load_all
打开文件但是如何修改数据并将其转储到同一个文件中。有一个方法 dump_all
,但不确定它的用法。
import yaml
with open('temp.yaml') as f:
temp = yaml.safe_load_all(f)
for t in temp:
if t['name'] == 'first':
t['cmp'][0]['Some'] = 'Result'
if t['name'] == 'second':
t['components']['parameters']['always_on'] = False
我如何将其转储回 temp.yaml
。所以它看起来像
%YAML 1.2
---
name: first
cmp:
- Some: Result
top:
top_rate: 16000
audio_device: "pulse"
---
name: second
components:
- name: second
parameters:
always_on: false
timeout: 200000
答案 0 :(得分:0)
使用'r+'
:
with open('temp.yaml', 'r+') as f:
temp = yaml.safe_load_all(f)
for t in temp:
if t['name'] == 'first':
t['cmp'][0]['Some'] = 'Result'
if t['name'] == 'second':
t['components']['parameters']['always_on'] = False
# reset to position 0
f.seek(0)
yaml.safe_dump_all(test, f)
# if new file is shorter than original file, truncate additional bytes
f.truncate()
请注意,空行不会被保留,因为它们会被 YAML 解析器丢弃。像 "pulse"
这样的带引号的标量将变为不带引号的,因为在将数据加载到本机结构时会丢失有关引号的信息。
有关保留样式的更多信息,请查看 this question。