[英]Download csv file using python 3
我是Python的新手。 這是我的環境設置:
我有Anaconda 3(Python 3)。 我希望能夠從以下網站下載CSV文件: https : //data.baltimorecity.gov/api/views/dz54-2aru/rows.csv?accessType= DOWNLOAD
我想使用請求庫。 感謝您提供幫助,以幫助我們確定如何使用請求庫將CSV文件下載到計算機上的本地目錄中
建議將數據下載為流,然后將其刷新到目標或中間本地文件中。
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
在這里,您可以通過請求庫獲得有關體流使用情況的更多詳細信息:
http://docs.python-requests.org/en/latest/user/advanced/#body-content-workflow
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.