0

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.