python - Rewriting specific line in JSON file -


{"channel_id": "345", "text": "hello ", "reminded": "false", "id": "25", "future": 1503253874} 

i have code write file called reminders.json. written file after commmand has been executed user.

now, have code value of "future", timestamp. proceed this

if timestamp <= int(time.time()):                            if jsondata["reminded"] == false:                 try:                     await client.send_message(destination=discord.user(id=jsondata["id"]), content="you asked me remind this:\n{}".format(text))                     #now since user has been alerted here,  change "reminded" true.                     jsondata['reminded'] = true                                          print("new json data =", jsondata)                     # problem here , not know how replace current line in loop, new json data (jsondata).                     except (discord.errors.forbidden, discord.errors.notfound):                     print("permission error") 

the problem here (where comment is) , not know how replace current line in loop, new json data (jsondata) , write reminders.json file.

as discussed in comments question, can't rewrite single line in file (unless know absolute certainty new line has exact same length), need either truncate file , rewrite point it's first changed, or rewrite file in entirety (which has benefits atomicity, anyhow).


here, we're using python-atomicwrites latter:

import json  # 3rd-party library atomicwrites import atomic_write  def rewritewithmodifieddata(filename, key, value):     open(filename, 'r') file_in:         data = json.load(file_in)     data[key] = value     atomic_write(filename, overwrite=true) file_out:         json.dump(data, file_out) 

...whereafter can run:

# note doing *should* (using boolean), not # asked (using string). rewritewithmodifieddata('reminders.json', 'reminded', true) 

for other approaches, see related questions , answers:


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -