I need to download the files stored inside a directory of a public ftp0 server, to later be able to generate a table with data extracted from them.
I've tried with various programs taken out of ftplib
but I get an error:
import sys
import ftplib
import os
from ftplib import FTP
ftp=FTP("ftp0------")
ftp.login("anonymous",----------)
def downloadFiles(path,destination):
#path & destination are str of the form "/dir/folder/something/"
#path should be the abs path to the root FOLDER of the file tree to download
try:
ftp.cwd(path)
#clone path to destination
os.chdir(destination)
os.mkdir(destination[0:len(destination)-1]+path)
print (destination[0:len(destination)-1]+path+" built")
except OSError:
#folder already exists at destination
pass
except ftplib.error_perm:
#invalid entry (ensure input form: "/dir/folder/something/")
print ("error: could not change to "+path)
sys.exit("ending session")
#list children:
filelist=ftp.nlst()
for file in filelist:
try:
#this will check if file is folder:
ftp.cwd(path+file+"/")
#if so, explore it:
downloadFiles(path+file+"/",destination)
except ftplib.error_perm:
#not a folder with accessible content
#download & return
os.chdir(destination[0:len(destination)-1]+path)
#possibly need a permission exception catch:
ftp.retrbinary("RETR "+file,
open(os.path.join(destination,file),"wb").write)
print (file + " downloaded")
return
source="/publico/-------/"
dest="/ftp0-------/expl/"
downloadFiles(source,dest)
I get the following error:
error: could not change to / public / ---- /
An exception has occurred, use% tb to see the full traceback.SystemExit: ending session
This other code does work but it does not print anything on the screen and the files do not come out.
import ftplib
# Connection information
server = 'ftp0.-------'
username = 'anonymous'
password = '-----'
# Directory and matching information
directory = '/expl/publico/MI_DIRECTORIO/'
filematch = '*.txt'
# Establish the connection
ftp = ftplib.FTP(server)
ftp.login(username, password)
# Change to the proper directory
ftp.cwd(directory)
# Loop through matching files and download each one individually
for filename in ftp.nlst(filematch):
fhandle = open(filename, 'wb')
print ('Getting ' + filename)
ftp.retrbinary('RETR ' + filename, fhandle.write)
fhandle.close()