Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to edit and save TOML content in Python

I would like to edit a local TOML file and save it again to be used in the same Python script. In this sense, to be able to change a given parameter in loop. You can see an example of file, here.

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

So far, I could load the file but I don't find how to change a parameter value.

import toml
data = toml.load("scenario.toml")
like image 244
R2D2 Avatar asked Jul 25 '26 04:07

R2D2


1 Answers

After reading a the file with the toml.load, you can modify your data then overwrite everything with the toml.dump command

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()
like image 173
Fouad Atwi Avatar answered Jul 26 '26 19:07

Fouad Atwi