【问题标题】:Python file input (write mode) issue with JSONJSON的Python文件输入(写入模式)问题
【发布时间】: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


    【解决方案1】:

    您似乎没有退出交互式提示来检查文件。关闭文件以刷新它:

    f.close()
    

    如果您也退出交互式提示,它也会关闭。

    【讨论】:

      猜你喜欢
      • 2011-09-20
      • 2021-05-07
      • 2011-09-15
      • 2019-10-12
      • 2021-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多