【问题标题】:Modifying content of NamedTemporaryFile (Python 3)修改 NamedTemporaryFile 的内容(Python 3)
【发布时间】:2016-02-15 21:14:24
【问题描述】:

在最初创建 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

感谢您的帮助!

【问题讨论】:

    标签: python json file-io temporary-files


    【解决方案1】:

    1:这一行:

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

    不会将content 转储到f。它从content 生成一个字符串,skipkeys 的值为f,然后什么都不做。

    你可能想要json.dump,没有s..

    2:这一行

        updated_file = json.loads(tempf)
    

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

    【讨论】:

    • 谢谢!这解决了我的问题。 IO小问题:如果我调用content = json.loads(open(json_filepath).read()),是否需要关闭文件之后才能再次写入?
    猜你喜欢
    • 1970-01-01
    • 2018-10-19
    • 2012-03-16
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 2010-10-26
    • 1970-01-01
    • 2010-12-09
    相关资源
    最近更新 更多