i'm learning python , i'm following official documentation from:
section: 7.2.2. saving structured data json python 3
i'm testing json.dump() function dump python set 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 exists in working directory , if didn't, statement f = open('testfile.txt', 'w', encoding='utf-8') have re-create it, truncated.
the json.dumps(response) converts response set valid json object, that's fine.
problem when use json.dumps(response, f) method, updates testfile.txt, gets truncated.
i've managed reverse workaround like:
>>> f = open('testfile.txt', 'w', encoding='utf-8') >>> f.write(json.dumps(response)); 56 >>> after contents of testfile.txt become expected:
{"success": true, "data": ["test", "array", "response"]} even, approach works too:
>>> json.dump(response, open('testfile.txt', 'w', encoding='utf-8')) why approach fail?:
>>> f = open('testfile.txt', 'w', encoding='utf-8') >>> json.dump(response, f) note don't errors console; truncated file.
it looks aren't exiting interactive prompt check file. close file flush it:
f.close() it close if exit interactive prompt well.
Comments
Post a Comment