Simple ftp download, without any abnormal judgment.
<span style= "FONT-SIZE:14PX;" >import osfrom ftplib Import ftpftp_addr = ' 10.10.0.1 ' f=ftp (ftp_addr) f.login (' Anonymous ') f.cwd ("apk_download/") remote_file = ' 20141223140651.apk ' f.retrbinary ("RETR%s"% remote_file, open (Remote_file, "WB"). Write) </span >
Search online for a version with exception handling from
Http://www.hiadmin.org/code/python-ftp
<span style= "FONT-SIZE:14PX;" >#! encoding:utf-8# filename:ftptestdown.py# Use the Ftplib.error_perm function to print output error messages import Ftplibimport Osimport Socketremote_ Host = "ftp.kernel.org" Remote_dir = "/pub/linux/kernel/v1.0" remote_file = "patch8.gz" Def Kernelmain (): try:ftp = Ftplib. FTP (Remote_host) except (Socket.error, socket.gaierror): print "Error cannot reach '%s '"% Remote_host re Turn print ". Connected to Remote_host '%s ': "%remote_host try:ftp.login () #使用匿名账号登陆也就是anonymous except Ftplib.error_perm : print "ERROR cannot login anonymously" ftp.quit () return print "... logged in as ' anonymously '. ." TRY:FTP.CWD (remote_dir) #切换当前工作目录 except Ftplib.error_perm:print "error cannot CD to '%s '"% Remote_dir Ftp.quit () return print ".... Changed to '%s ' folder ... "% Remote_dir try: #传一个回调函数给retrbinary () It is called when every binary data is received Ftp.retrbinary (" RETR%s "% Remote_file, open (Remote_file, "WB"). write) except Ftplib.error_perm:print "error cannot remote_file '%s '"% remote_file os.unlink (remote_fi Le) else:print "..... Download '%s ' to CWD ... "% remote_file ftp.quit () return# call function to execute test if __name__ = =" __main__ ": Kernelmain () < ;/span>
Python FTP Download File Simple example