How to download a file via FTP with Python ftplib

PythonFtpFtplib

Python Problem Overview


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()

Python Solutions


Solution 1 - Python

handle = open(path.rstrip("/") + "/" + filename.lstrip("/"), 'wb')
ftp.retrbinary('RETR %s' % filename, handle.write)

Solution 2 - Python

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"

Solution 3 - Python

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.

Solution 4 - Python

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

Solution 5 - Python

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()

Solution 6 - Python

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	

Solution 7 - Python

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIntekhab KhanView Question on Stackoverflow
Solution 1 - Pythonnumber23_cnView Answer on Stackoverflow
Solution 2 - PythonRakeshView Answer on Stackoverflow
Solution 3 - PythonRdBView Answer on Stackoverflow
Solution 4 - PythonguettliView Answer on Stackoverflow
Solution 5 - PythonJDaviesView Answer on Stackoverflow
Solution 6 - PythonIkerView Answer on Stackoverflow
Solution 7 - PythonGaurav ShrivastavaView Answer on Stackoverflow