如何在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")

读取文件后使用toml。您可以修改您的数据,然后用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()

最新更新