How to download a file via FTP with Python ftplib

后端 未结 7 1745
名媛妹妹
名媛妹妹 2020-12-05 12:51

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?

#         


        
相关标签:
7条回答
  • 2020-12-05 12:59

    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()
    
    0 讨论(0)
  • 2020-12-05 13:00

    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 
    
    0 讨论(0)
  • 2020-12-05 13:01
    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.

    0 讨论(0)
  • 2020-12-05 13:02
    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"
    
    0 讨论(0)
  • 2020-12-05 13:11
    handle = open(path.rstrip("/") + "/" + filename.lstrip("/"), 'wb')
    ftp.retrbinary('RETR %s' % filename, handle.write)
    
    0 讨论(0)
  • 2020-12-05 13:13

    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)
    
    0 讨论(0)
提交回复
热议问题