Python - update item in an existing json file -
i want update float
values
inside json
file, structured this:
{"starbucks": {"roads": 1.0, "pyramid song": 1.0, "go alone": 1.0}}
so whenever generate existing playlist, exact same items, increment key
values
+1.0
.
i have file opened 'append'
option
with open('pre_database/playlist.json', 'a') f: if os.path.exists('pre_database/playlist.json'): #update json here json.dump(playlist,f)
but 'a'
method append dictionary
json
, , generate parsing
problems later on.
likewise, if use 'w'
method, overwrite file entirely.
what best solution updating values?
you open file in r+
mode (opens file both reading , writing), read in json content, seek start of file, truncate , rewrite modified dictionary file:
if os.path.exists('pre_database/playlist.json'): open('pre_database/playlist.json', 'r+') f: playlist = json.load(f) # update json here f.seek(0) f.truncate() json.dump(playlist, f)
Comments
Post a Comment