简体   繁体   中英

Modifying content of NamedTemporaryFile (Python 3)

I'm unable to modify the content of a NamedTemporaryFile after having created it initially.

As per my example below, I create a NamedTemporaryFile from the content of a URL (JSON data).

Then, what I aim to do is re-access that file, modify some of the content of the JSON in the file, and save it. The code below is my attempt to do so.

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

Thanks for the help!

1: This line:

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

doesn't dump content to f . It makes a string from content , with skipkeys value f , and then does nothing with it.

You probably wanted json.dump , with no s ..

2: This line

    updated_file = json.loads(tempf)

tries to load a JSON object from the temp filename, which isn't going to work. You'll have to either read the file in as a string and then use loads , or re-open the file and use json.load .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM