How to edit and save TOML content in Python
Asked Answered
I

1

6

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")
Inflame answered 26/1, 2021 at 16:16 Comment(2)
did you check out the quickstart guide?Woolly
yes, I see how to parse but not editing on the flyInflame
A
9

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()
Archie answered 4/5, 2021 at 15:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.