Skip to content
Advertisement

emptying JSON file

I want to completely empty a JSON file, while still keeping the file. How do I do that? I tried:

with open("Screentime/activities.json", "w") as f:
    json.dump("", f, indent=4, sort_keys=True)
with open("Screentime/activities.json", "w") as f:
    json.dump({}, f, indent=4, sort_keys=True)

, etc but none of them work. Please help me out! Ive seen answers on how to delete keys in the JSON, or delete the entire file, but not how to just replace it with nothing.

Advertisement

Answer

You can just open and close the file in ‘w’ mode:

open('Screentime/activities.json', 'w').close()

This is going to remove completely any content from your file. In other words, your file will be empty.

EDIT: While this answer does provide the result the OP asked for, it should be noted that an empty file is not a valid JSON file. More details can be found here.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement