这是我的YAML文件(data.yaml
):
- Department: "IT"
name: "abcd"
Education: "Bachlore of Engineering"
我想按如下方式对其进行编辑:
- Department: "IT"
name: "abcd"
Education: "Bachlore of Engineering"
- Department: "Production"
name: "xyz"
Education: "Bachlore of Engineering"
- Department: "Management"
name: "ab"
Education: "MBA"
这是我的代码(当前仅添加第二个列表):
from pathlib import Path
from ruamel.yaml import YAML
from ruamel.yaml.scalarstring import SingleQuotedScalarString, DoubleQuotedScalarString
datapath= Path('C:/Users/Master 1TB/source/repos/check2/check2/data.yaml')
with YAML(output=datapath) as yaml:
yaml.indent(sequence=4, offset=2)
code = yaml.load(datapath)
code = [{
"Department": "Production"
"name": "xyz"
"Education": "Bachlore of Engineering"
}]
yaml.dump(code)
现在,当代码将新列表转储到data.yaml
中时,问题就被删除了,因此我的输出是:
- Department: "Production"
name: "xyz"
Education: "Bachlore of Engineering"
相反,我希望输出中也包含上一个项目,正如您在链接(How to read a component in YAML file so that I can edit it's key value using ruamel.yaml?)中所述,我必须附加新的列表值,但这只有在我有一个列表值的情况下才可以。 br />
在这种情况下可以做什么?
另外,我还将在data.yaml
中添加更多列表值(将所有更早的列表保留在同一YAML文件中)。
答案 0 :(得分:0)
您在 post '/rails/active_storage/direct_uploads', to: 'direct_uploads#create'
文件的根目录下有一个序列,并且在加载时
在您的可变代码中获取列表。之后,您将分配给data.yaml
和需要执行的操作
是code
列表中的一项,或append
包含一个或多个项目的列表。
您不能真正做的另一件事是具有相同的文件以供读取
并在with语句中使用extend
参数时编写。写入另一个文件
或从文件加载,然后将更新的结构转储到同一文件。
您还应该确保键值对之间有逗号,因为现在您的代码将无法运行。
output
给出:
import sys
from pathlib import Path
from ruamel.yaml import YAML
from ruamel.yaml.scalarstring import SingleQuotedScalarString, DoubleQuotedScalarString
datapath = Path('data.yaml')
yaml = YAML()
code = yaml.load(datapath)
code.extend([{
"Department": "Production",
"name": "xyz",
"Education": "Bachlore of Engineering",
}])
yaml.dump(code, datapath)
print(datapath.read_text())