Fetch files from FTP with Python

5254
1
03-01-2011 04:44 AM
SoniaSandiago
New Contributor
Hi all you Pythoners,

I am fairly new to this , but using online resources I have put together a script that fetches one file from an ftp connection (Python 2.5 on windows xp). I would like to download all the files within a specific directory but I am having trouble with the syntax of for/batch/iteration loop. This is what I have so far:

-----------------------------------------------------------------------------------------------
# Import the FTP object from ftplib
from ftplib import FTP
import os, sys


# This will handle the data being downloaded
def handleDownload(block):
    file.write(block)
    print ".",
   
# Create an instance of the FTP object
# FTP('hostname', 'username', 'password')
ddir='C:\\GISData\\test\\'
os.chdir(ddir)

ftp = FTP('ftptest.int')

# Log in to the server
print 'Logging in.'
# You can specify username and password here :
ftp.login('user1', 'testpassword')


# This is the directory that we want to go to
directory = '\\GIS\\test\\datatest'
# Change to that directory. 
print 'Changing to ' + directory
ftp.cwd(directory)

# Print the contents of the directory
ftp.retrlines('LIST')

# file name to acquire.
filename = 'boundary.shp'
#for file in directory:

# 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
print 'Closing file ' + filename
file.close()

print 'Closing FTP connection'
ftp.close()

----------------------------------------------------------------------------------------------

Any suggestions?
Thanks!
0 Kudos
1 Reply
NickDeMerchant
New Contributor
Hi Sonia,

I would like to try and run your code through however am having problems with this snippet....Are you able to assist?  Should there be any more code?

# This will handle the data being downloaded
def handleDownload(block):
file.write(block)
print ".",


Thanks,

Nick
0 Kudos