Reputation: 4097
I'm learning Python and I'm following official documentation from:
Section: 7.2.2. Saving structured data with json for Python 3
I'm testing the json.dump()
function to dump my python set into a file pointer:
>>> response = {"success": True, "data": ["test", "array", "response"]}
>>> response
{'success': True, 'data': ['test', 'array', 'response']}
>>> import json
>>> json.dumps(response)
'{"success": true, "data": ["test", "array", "response"]}'
>>> f = open('testfile.txt', 'w', encoding='UTF-8')
>>> f
<_io.TextIOWrapper name='testfile.txt' mode='w' encoding='UTF-8'>
>>> json.dump(response, f)
The file testfile.txt
already exists in my working directory and even if it didn't, statement f = open('testfile.txt', 'w', encoding='UTF-8')
would have re-create it, truncated.
The json.dumps(response)
converts my response
set into a valid JSON object, so that's fine.
Problem is when I use the json.dumps(response, f)
method, which actually updates my testfile.txt
, but it gets truncated.
I've managed to do a reverse workaround like:
>>> f = open('testfile.txt', 'w', encoding='UTF-8')
>>> f.write(json.dumps(response));
56
>>>
After which the contents of my testfile.txt
become as expected:
{"success": true, "data": ["test", "array", "response"]}
Even, this approach works too:
>>> json.dump(response, open('testfile.txt', 'w', encoding='UTF-8'))
Why does this approach fail?:
>>> f = open('testfile.txt', 'w', encoding='UTF-8')
>>> json.dump(response, f)
Note that I don't get any errors from the console; just a truncated file.
Upvotes: 0
Views: 542
Reputation: 177674
It looks like you aren't exiting the interactive prompt to check the file. Close the file to flush it:
f.close()
It will close if you exit the interactive prompt as well.
Upvotes: 2