Python downloads data from ftp to save the instance

Source: Internet
Author: User

The weather data of the hadoop authoritative guide can be found in

Copy codeThe Code is as follows:
#! /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) # enable debug level 2 and display details
Ftp. connect (ftp_server, 21) # connect
Ftp. login (username, password) # log on. If you log on anonymously, use an empty string instead.
Return ftp

Def downloadfile ():
Ftp = ftpconnect ()
# Print ftp. getwelcome () # display ftp server welcome information
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 # Place the date at the beginning to facilitate sorting
Bufsize = 1024 # Set the buffer block size
Fp = open (localpath, 'wb ') # open a file locally in write mode
Ftp. retrbinary ('RETR' + eachFile, fp. write, bufsize) # receives files from the server and writes them to local files.
Year = year + 1
Ftp. set_debuglevel (0) # disable debugging
Fp. close ()
Ftp. quit () # exit the ftp server


If _ name __= = "_ main __":
Downloadfile ()

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.