HEA*_*0NE 2 python file-io json 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
Run Code Online (Sandbox Code Playgroud)
谢谢您的帮助!
1:这一行:
json.dumps(content, f, indent=4) # Issue: Nothing is written to f
Run Code Online (Sandbox Code Playgroud)
不会转储content到f. 它从content, 和skipkeysvalue 生成一个字符串,f然后什么都不做。
你可能想要json.dump,没有s..
2:这条线
updated_file = json.loads(tempf)
Run Code Online (Sandbox Code Playgroud)
尝试从临时文件名加载 JSON 对象,但这是行不通的。您必须将文件作为字符串读入,然后使用loads,或者重新打开文件并使用json.load.