json.dump not writing to file
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?
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