在最初创建 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
生成一个带有 skipkeys
值 f
的字符串,然后不对其执行任何操作。
您可能想要 json.dump
,但没有 s
..
2:这一行
updated_file = json.loads(tempf)
尝试从临时文件名加载 JSON 对象,但这不起作用。您必须将文件作为字符串读取,然后使用 loads
,或者重新打开文件并使用 json.load
。
关于python - 修改NamedTemporaryFile的内容(Python 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35419215/