#clearing json file before dump

12 messages · Page 1 of 1 (latest)

quiet kelp
#
import json

with open('data.json', 'r+') as json_file:

    data: dict = json.load(json_file)

    # editing data here

    json.dump(data, json_file, indent=4) # this just adds it to the end
#

in simple, just need to know how to clear a file

#

tried using .truncate(0) but it comes up with this?

true mango
#

I'd just open at as read then open it as write

#

with open('data.json') as f:
    data = json.load(f)

# modify

with open('data.json', 'w') as f:
    json.dump(data, f, indent=4)
quiet kelp
#

wouldnt it still append to the end of the json like that?

true mango
#

No, 'w' truncates

quiet kelp
#

ah

keen horizon
#

yes using w will fix it

true mango
#

I've never had good experiences with opening as multiple things like 'r+' but that might be a skillissue 😄

still oracleBOT
still oracleBOT