我有以下代码,可以轻松连接到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()
答案 0 :(得分:64)
handle = open(path.rstrip("/") + "/" + filename.lstrip("/"), 'wb')
ftp.retrbinary('RETR %s' % filename, handle.write)
答案 1 :(得分:29)
A = filename
ftp = ftplib.FTP("IP")
ftp.login("USR Name", "Pass")
ftp.cwd("/Dir")
try:
ftp.retrbinary("RETR " + filename ,open(i, 'wb').write)
except:
print "Error"
答案 2 :(得分:10)
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)
当然,处理可能的错误是明智的。
答案 3 :(得分:7)
可以将Python标准库中的ftplib
模块与汇编程序进行比较。使用高级库,例如:https://pypi.python.org/pypi/ftputil
答案 4 :(得分: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
答案 5 :(得分:1)
请注意,如果要从FTP下载到本地,则需要使用以下内容:
with open( filename, 'wb' ) as file :
ftp.retrbinary('RETR %s' % filename, file.write)
否则,该脚本将位于本地文件存储而不是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()
答案 6 :(得分:0)
如果您不仅限于使用ftplib
,还可以尝试wget
模块。这是代码段
import wget
file_loc = 'http://www.website.com/foo.zip'
wget.download(file_loc)