如何使用Python ftplib通过FTP下载文件

Int*_*han 60 python ftplib

我有以下代码,可以轻松连接到FTP服务器并打开一个zip文件.我想将该文件下载到本地系统.怎么做?

# 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()
Run Code Online (Sandbox Code Playgroud)

num*_*_cn 68

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

  • 可以使用一些上下文。理想情况下,正如其他人提到的,您在 `with` 语句中调用此命令来管理您的文件描述符并自动为您关闭它! (5认同)

Rak*_*esh 29

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"
Run Code Online (Sandbox Code Playgroud)


RdB*_*RdB 11

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)
Run Code Online (Sandbox Code Playgroud)

当然,我们应该明智地处理可能的错误.


JDa*_*ies 8

请注意,如果您是从 FTP 下载到本地,则需要使用以下内容:

with open( filename, 'wb' ) as file :
        ftp.retrbinary('RETR %s' % filename, file.write)
Run Code Online (Sandbox Code Playgroud)

否则,脚本将在您的本地文件存储而不是 FTP。

我自己花了几个小时才犯了这个错误。

脚本如下:

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()
Run Code Online (Sandbox Code Playgroud)


gue*_*tli 7

ftplib可以将Python标准库中的模块与汇编程序进行比较.使用高级库,如:https://pypi.python.org/pypi/ftputil


Ike*_*ker 6

这是一个适合我的Python代码.评论是西班牙语,但该应用程序很容易理解

# 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 
Run Code Online (Sandbox Code Playgroud)