Рекомендуется загружать данные в виде потока и выгружать их в целевой или промежуточный локальный файл.
import requests
def download_file(url, output_file, compressed=True):
"""
compressed: enable response compression support
"""
# NOTE the stream=True parameter. It enable a more optimized and buffer support for data loading.
headers = {}
if compressed:
headers["Accept-Encoding"] = "gzip"
r = requests.get(url, headers=headers, stream=True)
with open(output_file, 'wb') as f: #open as block write.
for chunk in r.iter_content(chunk_size=4096):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
f.flush() #Afterall, force data flush into output file (optional)
return output_file
Учитывая оригинальный пост:
remote_csv = "https://data.baltimorecity.gov/api/views/dz54-2aru/rows.csv?accessType=DOWNLOAD"
local_output_file = "test.csv"
download_file(remote_csv, local_output_file)
#Check file content, just for test purposes:
print(open(local_output_file).read())
Базовый код был извлечен из этого поста: https://stackoverflow.com/a/16696317/176765
Здесь вы можете получить более подробную информацию об использовании потока тела с запросами Lib:
http://docs.python-requests.org/en/latest/user/advanced/#body-content-workflow
Вы обнаружили, что так лучше lution? Я считаю, что вы можете настроить размер буфера для лучшей производительности выборки. – apast