【发布时间】:2016-01-29 03:58:20
【问题描述】:
我正在学习 Python,我正在关注以下官方文档:
部分:7.2.2. Saving structured data with json 用于 Python 3
我正在测试 json.dump() 函数以将我的 python 集转储到文件指针中:
>>> 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)
文件testfile.txt 已经存在于我的工作目录中,即使它不存在,语句f = open('testfile.txt', 'w', encoding='UTF-8') 也会重新创建它,被截断。
json.dumps(response) 将我的 response 集转换为有效的 JSON 对象,这很好。
问题是当我使用json.dumps(response, f) 方法时,它实际上更新了我的testfile.txt,但它被截断了。
我设法做了一个反向解决方法,例如:
>>> f = open('testfile.txt', 'w', encoding='UTF-8')
>>> f.write(json.dumps(response));
56
>>>
之后我的testfile.txt的内容就变成了预期的样子:
{"success": true, "data": ["test", "array", "response"]}
甚至,这种方法也有效:
>>> json.dump(response, open('testfile.txt', 'w', encoding='UTF-8'))
为什么这种方法会失败?:
>>> f = open('testfile.txt', 'w', encoding='UTF-8')
>>> json.dump(response, f)
请注意,我没有从控制台收到任何错误;只是一个截断的文件。
【问题讨论】:
标签: python json file-handling