FTP Download Example : ftp « Network « Python Tutorial






import ftplib
import os
import socket

HOST = 'ftp.mozilla.org'
DIRN = 'pub/mozilla.org/webtools'
FILE = 'bugzilla-LATEST.tar.gz'

try:
    f = ftplib.FTP(HOST)
except (socket.error, socket.gaierror), e:
    print 'ERROR: cannot reach "%s"' % HOST
    return
print '*** Connected to host "%s"' % HOST

try:
    f.login()
except ftplib.error_perm:
    print 'ERROR: cannot login anonymously'
    f.quit()
    return
print '*** Logged in as "anonymous"'

try:
    f.cwd(DIRN)
except ftplib.error_perm:
    print 'ERROR: cannot CD to "%s"' % DIRN
    f.quit()
    return
print '*** Changed to "%s" folder' % DIRN

try:
    f.retrbinary('RETR %s' % FILE,
          open(FILE, 'wb').write)
except ftplib.error_perm:
    print 'ERROR: cannot read file "%s"' % FILE
    os.unlink(FILE)
else:
    print '*** Downloaded "%s" to CWD' % FILE
f.quit()
return








21.24.ftp
21.24.1.Using Python to Fetch Files from an FTP Server
21.24.2.Interactive FTP Example
21.24.3.FTP Download Example
21.24.4.Binary file download
21.24.5.ASCII file download
21.24.6.Binary file upload
21.24.7.Binary file download 2
21.24.8.Basic FTP connection
21.24.9.File dir() example
21.24.10.Parse return value from dir() function
21.24.11.FTP nlst example
21.24.12.nlst() with file/directory detection example