我有一个Python dict,它来自于通常读取YAML文件
yaml.load(stream)
Run Code Online (Sandbox Code Playgroud)
我想以编程方式更新YAML文件给定要更新的路径,如:
1组,选项1,option11,值
并将生成的dict再次保存为yaml文件.考虑到路径是动态的(假设用户能够通过我使用Cmd创建的简单CLI进入路径),我面临更新二项决定的问题.
有任何想法吗?
谢谢!
更新 让我在这个问题上更加具体:问题是更新字典的一部分,我事先并不知道结构.我正在开发一个项目,其中所有配置都存储在YAML文件中,我想添加一个CLI以避免必须手动编辑它们.这是一个示例YAML文件,使用PyYaml加载到字典(config-dict):
config:
a-function: enable
b-function: disable
firewall:
NET:
A:
uplink: enable
downlink: enable
B:
uplink: enable
downlink: enable
subscriber-filter:
cancellation-timer: 180
service:
copy:
DS: enable
remark:
header-remark:
DSC: enable
remark-table:
port:
linkup-debounce: 300
p0:
mode: amode
p1:
mode: bmode
p2:
mode: amode
p3:
mode: bmode
Run Code Online (Sandbox Code Playgroud)
我用Cmd创建了CLI,即使使用自动完成它也能很好地工作.用户可以提供如下行:
config port p1 mode amode
Run Code Online (Sandbox Code Playgroud)
所以,我需要编辑:
config-dict ['config'] ['port'] ['p1'] ['mode']并将其设置为'amode'.然后,使用yaml.dump()再次创建该文件.另一条可能的路线是:
config a-function enable
Run Code Online (Sandbox Code Playgroud)
所以config-dict ['config'] ['a-function']必须设置为'enable'.
我的问题是更新字典时.如果Python传递值作为引用将很容易:只需遍历dict直到找到正确的值并保存它.实际上这就是我为Cmd自动完成所做的事情.但我不知道如何进行更新.
希望我现在更好地解释自己!
提前致谢.
Jan*_*sky 16
事实上,解决方案遵循简单的模式:load - modify - dump:
在播放之前,请确保安装了pyyaml:
$ pip install pyyaml
Run Code Online (Sandbox Code Playgroud)
testyaml.pyimport yaml
fname = "data.yaml"
dct = {"Jan": {"score": 3, "city": "Karvina"}, "David": {"score": 33, "city": "Brno"}}
with open(fname, "w") as f:
yaml.dump(dct, f)
with open(fname) as f:
newdct = yaml.load(f)
print newdct
newdct["Pipi"] = {"score": 1000000, "city": "Stockholm"}
with open(fname, "w") as f:
yaml.dump(newdct, f)
Run Code Online (Sandbox Code Playgroud)
data.yaml$ cat data.yaml
David: {city: Brno, score: 33}
Jan: {city: Karvina, score: 3}
Pipi: {city: Stockholm, score: 1000000}
Run Code Online (Sandbox Code Playgroud)