Json. Dump Not Writing to File

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

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

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest