我正在尝试使用JSON
模块将大requests
个文件保存到变量中,但在使用以下内容时,只有部分JSON
正在将其变为变量:
r = requests.get(url)
r.json()
我看到有些方法可以在写入文件时将其保存在块中是否可以在写入变量时执行此操作?
答案 0 :(得分:1)
根据docs,使用''并将流设置为True应该可以满足您的需求。
with requests.get('http://httpbin.org/get', stream=True) as r:
# Do things with the response here.
答案 1 :(得分:0)
response = requests.get(url, stream=True)
with open(path, 'wb') as f:
for chunk in response.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
response.close()
或者您可以使用上下文管理器:
with requests.get(url, stream=True) as response:
with open(path, 'wb') as f:
for chunk in response.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
对于变量,它是相同的,只需使用data += chunk