[python] How to download a file via FTP with Python ftplib

I have the following code which easily connects to the FTP server and opens a zip file. I want to download that file into the local system. How to do that?

# Open the file for writing in binary mode
print 'Opening local file ' + filename
file = open(filename, 'wb')

# Download the file a chunk at a time
# Each chunk is sent to handleDownload
# We append the chunk to the file and then print a '.' for progress
# RETR is an FTP command

print 'Getting ' + filename
ftp.retrbinary('RETR ' + filename, handleDownload)

# Clean up time
print 'Closing file ' + filename
file.close()

This question is related to python ftplib

The answer is


A = filename

ftp = ftplib.FTP("IP")
ftp.login("USR Name", "Pass")
ftp.cwd("/Dir")


try:
    ftp.retrbinary("RETR " + filename ,open(A, 'wb').write)
except:
    print "Error"

If you are not limited to using ftplib you can also give wget module a try. Here, is the snippet

import wget
file_loc = 'http://www.website.com/foo.zip'
wget.download(file_loc)

This is a Python code that is working fine for me. Comments are in Spanish but the app is easy to understand

# coding=utf-8

from ftplib import FTP                                                                      # Importamos la libreria ftplib desde FTP

import sys

def imprimirMensaje():                                                                      # Definimos la funcion para Imprimir el mensaje de bienvenida
    print "------------------------------------------------------"
    print "--               COMMAND LINE EXAMPLE               --"
    print "------------------------------------------------------"
    print ""
    print ">>>             Cliente FTP  en Python                "
    print ""
    print ">>> python <appname>.py <host> <port> <user> <pass>   "
    print "------------------------------------------------------"

def f(s):                                                                                   # Funcion para imprimir por pantalla los datos 
    print s

def download(j):                                                                            # Funcion para descargarnos el fichero que indiquemos según numero    
    print "Descargando=>",files[j]      
    fhandle = open(files[j], 'wb')
    ftp.retrbinary('RETR ' + files[j], fhandle.write)                                       # Imprimimos por pantalla lo que estamos descargando        #fhandle.close()
    fhandle.close()                                                     

ip          = sys.argv[1]                                                                   # Recogemos la IP       desde la linea de comandos sys.argv[1] 
puerto      = sys.argv[2]                                                                   # Recogemos el PUERTO   desde la linea de comandos sys.argv[2]
usuario     = sys.argv[3]                                                                   # Recogemos el USUARIO  desde la linea de comandos sys.argv[3]
password    = sys.argv[4]                                                                   # Recogemos el PASSWORD desde la linea de comandos sys.argv[4]


ftp = FTP(ip)                                                                               # Creamos un objeto realizando una instancia de FTP pasandole la IP
ftp.login(usuario,password)                                                                 # Asignamos al objeto ftp el usuario y la contraseña

files = ftp.nlst()                                                                          # Ponemos en una lista los directorios obtenidos del FTP

for i,v in enumerate(files,1):                                                              # Imprimimos por pantalla el listado de directorios enumerados
    print i,"->",v

print ""
i = int(raw_input("Pon un Nº para descargar el archivo or pulsa 0 para descargarlos\n"))    # Introducimos algun numero para descargar el fichero que queramos. Lo convertimos en integer

if i==0:                                                                                    # Si elegimos el valor 0 nos decargamos todos los ficheros del directorio                                                                               
    for j in range(len(files)):                                                             # Hacemos un for para la lista files y
        download(j)                                                                         # llamamos a la funcion download para descargar los ficheros
if i>0 and i<=len(files):                                                                   # Si elegimos unicamente un numero para descargarnos el elemento nos lo descargamos. Comprobamos que sea mayor de 0 y menor que la longitud de files 
    download(i-1)                                                                           # Nos descargamos i-1 por el tema que que los arrays empiezan por 0 

The ftplib module in the Python standard library can be compared to assembler. Use a high level library like: https://pypi.python.org/pypi/ftputil


Please note if you are downloading from the FTP to your local, you will need to use the following:

with open( filename, 'wb' ) as file :
        ftp.retrbinary('RETR %s' % filename, file.write)

Otherwise, the script will at your local file storage rather than the FTP.

I spent a few hours making the mistake myself.

Script below:

import ftplib

# Open the FTP connection
ftp = ftplib.FTP()
ftp.cwd('/where/files-are/located')


filenames = ftp.nlst()

for filename in filenames:

    with open( filename, 'wb' ) as file :
        ftp.retrbinary('RETR %s' % filename, file.write)

        file.close()

ftp.quit()

FILENAME = 'StarWars.avi'    

with ftplib.FTP(FTP_IP, FTP_LOGIN, FTP_PASSWD) as ftp:
    ftp.cwd('movies')
    with open(FILENAME, 'wb') as f:
        ftp.retrbinary('RETR ' + FILENAME, f.write)

Of course it would we be wise to handle possible errors.