python - 修改NamedTemporaryFile的内容(Python 3)

标签 python json file-io temporary-files

在最初创建 NamedTemporaryFile 后,我无法修改它的内容。

按照下面的示例,我根据 URL 的内容(JSON 数据)创建一个 NamedTemporaryFile。

然后,我要做的就是重新访问该文件,修改文件中 JSON 的一些内容,然后保存。下面的代码是我的尝试。

import json
import requests

from tempfile import NamedTemporaryFile


def create_temp_file_from_url(url):
    response = requests.get(url)
    temp_file = NamedTemporaryFile(mode='w+t', delete=False)
    temp_file.write(response.text)
    temp_file.close()
    return temp_file.name


def add_content_to_json_file(json_filepath):
    file = open(json_filepath)
    content = json.loads(file.read())

    # Add a custom_key : custom_value pair in each dict item
    for repo in content:
        if isinstance(repo, dict):
            repo['custom_key'] = 'custom_value'

    # Close file back ... if needed?
    file.close()

    # Write my changes to content back into the file
    f = open(json_filepath, 'w')   # Contents of the file disappears...?
    json.dumps(content, f, indent=4)  # Issue: Nothing is written to f
    f.close()

if __name__ == '__main__':
    sample_url = 'https://api.github.com/users/mralexgray/repos'

    tempf = create_temp_file_from_url(sample_url)

    # Add extra content to Temporary file
    add_content_to_json_file(tempf)

    try:
        updated_file = json.loads(tempf)
    except Exception as e:
        raise e

感谢您的帮助!

最佳答案

1:这一行:

json.dumps(content, f, indent=4)  # Issue: Nothing is written to f

不会将内容转储到f。它从 content 生成一个带有 skipkeysf 的字符串,然后不对其执行任何操作。

您可能想要 json.dump,但没有 s..

2:这一行

    updated_file = json.loads(tempf)

尝试从临时文件名加载 JSON 对象,但这不起作用。您必须将文件作为字符串读取,然后使用 loads,或者重新打开文件并使用 json.load

关于python - 修改NamedTemporaryFile的内容(Python 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35419215/

相关文章:

c++ - 如何在不逐字符遍历文件的情况下读取文件中的特定字符?

c# - 如何使用 .NET 快速获取目录中最旧的文件?

c - 在文本文件中读取错误的整数

python - 通过使用位数组而不是 int 来节省 dict 的内存?

python - 获取返回函数值的第一项

Python PPTX 条形图负值

java - 使用 java 迭代 JSON 响应中存在的最后一个值

Python游戏 Action

json - 使用 jq 展平嵌套的 JSON

android - 使用 google-api-java-client-1.15.0-rc 创建请求工厂