如何在 Python 中编辑和保存 TOML 内容

问题描述

我想编辑一个本地 TOML 文件并再次保存以在同一个 Python 脚本中使用。从这个意义上说,能够在循环中更改给定参数。您可以在此处查看文件示例。

https://bitbucket.org/robmoss/particle-filter-for-python/src/master/src/pypfilt/examples/predation.toml

到目前为止,我可以加载文件,但我没有找到如何更改参数值。

import toml
data = toml.load("scenario.toml")

解决方法

我不确定这个问题在 3 个月后现在是否仍然相关。

我没有任何经验。我看到你的问题是因为我正在寻找答案,我想我能够解决它。

可以做的是在使用 toml.load 读取文件后,您可以修改数据,然后使用 toml.dump 命令覆盖所有内容

import toml
data = toml.load("scenario.toml") 

# Modify field
data['component']['model']='NEWMODELNAME' # Generic item from example you posted

# To use the dump function,you need to open the file in 'write' mode
# It did not work if I just specify file location like in load
f = open("scenario.toml",'w')
toml.dump(data,f)
f.close()