2015-10-19 121 views
0

我是Python新手。這裏是我的環境設置:使用python下載csv文件3

我有Anaconda 3(Python 3)。我希望能夠從網站上下載CSV文件: https://data.baltimorecity.gov/api/views/dz54-2aru/rows.csv?accessType=DOWNLOAD

我想使用請求庫。我將不勝感激任何幫助,以確定我如何使用請求庫將CSV文件下載到本機上的本地目錄

+0

你有沒有找到更好的lution?我相信您可以調整緩衝區的大小以獲得更好的獲取性能。 – apast

回答

1

建議將數據下載爲流,並將其刷新到目標或中間本地文件中。

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

+1

在這裏感謝我使用的代碼。這可能聽起來很基本,並希望任何更改/更新,使其更好:導入請求 r = requests.get(「https://data.baltimorecity.gov/api/views/dz54-2aru/rows.csv? ('test.csv','wb')作爲f: f.write(r.content) – user3049935

+0

考慮編輯後的文章作爲一般下載目的代碼。您可以使用任何內容格式。 – apast