Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

json.dump not writing to file

Writer Olivia Zamora

I used the dump function like this with a file called test.py:

import json
li = [2, 5]
test = open('test.json', 'w')
json.dump(li, test)

But it didn't write to the JSON file after the code ran. Why is this? What is the correct way to use json.dump?

4

1 Answer

Changes are usually written to disk in blocks, usually on the order of 2 or 4KiB or so. Since your test file is tiny, the changes are not flushed from the REPL until you close the file, or the REPL or your script terminates.

Files have a close method you can use to close explicitly. However, the idiomatic way to work with files in python is using a with block:

import json
li = [2, 5]
with open('test.json', 'w') as test: json.dump(li, test)

This is roughly, equivalent to

li = [2, 5]
test = open('test.json', 'w')
try: json.dump(li, test)
finally: test.close()
4

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy