1
votes

I am trying to download files from an ftp server to a local folder. Below I have included my code, the script is able to access the ftp succesfully and list the names of the files on the ftp server however where my issue lies is I am not sure how to download them to a local directory.

from ftplib import FTP
import os, sys, os.path

def handleDownload(block):
    file.write(block)

ddir='U:/Test Folder'
os.chdir(ddir)
ftp = FTP('sidads.colorado.edu')
ftp.login()

print ('Logging in.')
directory = '/pub/DATASETS/NOAA/G02158/unmasked/2012/04_Apr/'

print ('Changing to ' + directory)
ftp.cwd(directory)
ftp.retrlines('LIST')

print ('Accessing files')

filenames = ftp.nlst() # get filenames within the directory
print (filenames)

I tried using the following code below however it gives me the error in the photo below.

for filename in filenames:
    if filename != '.':
        local_filename = os.path.join('U:/Test Folder/',                   filename)
    file = open(local_filename, 'wb')
    ftp.retrbinary('RETR '+ filename, file.write)
    file.close()
ftp.quit()

enter image description here

1
missing the errorDavid Bern
Thank you added the erroruser7220644
Are you trying to write the downloaded files into a zip file? local_filename will end up being something like 'U:/Test Folder/New WinZip File.zip/filename.txt which is probably not what you want. Also you need to indent the next 3 lines to be inside the if statement.Martin Evans
well. It seems you got an permission denied. You wouldnt have to take a picture. The relevant info is in the bottom. Errno 13 'C:/ArcGis/New folder\\.' The filename seems odd.David Bern
Yes Martin Evans I am trying to write all the zip files in the ftp server to the folder but am struggling to figure out how.user7220644

1 Answers

1
votes

Try the following:

for filename in filenames:
    if filename not in ['.', '..']:
        local_filename = os.path.join(ddir, filename)

        with open(local_filename, 'wb') as f_output:
            ftp.retrbinary('RETR '+ filename, f_output.write)

ftp.quit()

Your code was still attempting to download . filenames. You need to indent the writing of the valid filenames. Also by using with it will close the file automatically.