修改 NamedTemporaryFile 的内容 (Python 3)
Modifying content of NamedTemporaryFile (Python 3)
我无法在最初创建 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
不会将 content
转储到 f
。它从 content
生成一个字符串,skipkeys
值为 f
,然后什么也不做。
您可能想要 json.dump
,没有 s
..
2:这一行
updated_file = json.loads(tempf)
尝试从临时文件名加载一个 JSON 对象,但这是行不通的。您必须将文件作为字符串读入,然后使用 loads
,或者重新打开文件并使用 json.load
.
我无法在最初创建 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
不会将 content
转储到 f
。它从 content
生成一个字符串,skipkeys
值为 f
,然后什么也不做。
您可能想要 json.dump
,没有 s
..
2:这一行
updated_file = json.loads(tempf)
尝试从临时文件名加载一个 JSON 对象,但这是行不通的。您必须将文件作为字符串读入,然后使用 loads
,或者重新打开文件并使用 json.load
.