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

R2D*_*2D2 6 python loops save toml

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

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

到目前为止,我可以加载该文件,但我不知道如何更改参数值。

import toml
data = toml.load("scenario.toml")
Run Code Online (Sandbox Code Playgroud)

小智 9

使用 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()
Run Code Online (Sandbox Code Playgroud)