python從ftp下載資料儲存執行個體_python

來源:互聯網
上載者:User

《hadoop權威指南》的天氣資料可以在ftp://ftp3.ncdc.noaa.gov/pub/data/noaa下載,在網上看到這個資料好開心,開啟ftp發現個問題,呀呀,這麼多檔案啊,我一個個去點另存新檔,得點到啥時候啊,迅雷應該有批量下載,只是我沒找到,估計是我瀏覽器把迅雷禁掉了,乾脆自己用python寫一個實現下載好了,網上早了一下,發現很簡單啊

複製代碼 代碼如下:

#!/usr/bin/python
#-*- coding: utf-8 -*-

from ftplib import FTP

def ftpconnect():
    ftp_server = 'ftp3.ncdc.noaa.gov'
    username = ''
    password = ''
    ftp=FTP()
    ftp.set_debuglevel(2) #開啟調試層級2,顯示詳細資料
    ftp.connect(ftp_server,21) #串連
    ftp.login(username,password) #登入,如果匿名登入則用空串代替即可
    return ftp

def downloadfile(): 
    ftp = ftpconnect()   
    #print ftp.getwelcome() #顯示ftp伺服器歡迎資訊
    datapath = "/pub/data/noaa/"
    year=1911
    while year<=1930:
        path=datapath+str(year)
        li = ftp.nlst(path)
        for eachFile in li:
            localpaths = eachFile.split("/")
            localpath = localpaths[len(localpaths)-1]
            localpath='weatherdata/'+str(year)+'--'+localpath#把日期放在最前面,方便排序
            bufsize = 1024 #設定緩衝塊大小     
            fp = open(localpath,'wb') #以寫入模式在本地開啟檔案
            ftp.retrbinary('RETR ' + eachFile,fp.write,bufsize) #接收伺服器上檔案並寫入本地檔案
        year=year+1
    ftp.set_debuglevel(0) #關閉調試
    fp.close()
    ftp.quit() #退出ftp伺服器


if __name__=="__main__":
    downloadfile()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.