Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Using Python to Fetch Files from an FTP Server

ftp = ftplib.FTP('ftp.novell.com', 'anonymous',                  'bwdayley@novell.com')
gFile = open("readme.txt", "wb")
ftp.retrbinary('RETR Readme', gFile.write)

A common and extremely useful function of Python scripts is to retrieve files to be processed using the FTP protocol. The ftplib module included in Python allows you to use Python scripts to quickly attach to an FTP server, locate files, and then download them to be processed locally.

To open a connection to the FTP server, create an FTP server object using the ftplib.FTP([host [, user [, passwd]]]) method.

Once the connection to the server is opened, the methods in the ftplib module provide most of the FTP functionality to navigate the directory structure, manage files and directories, and, of course, download files.

The example shows connecting to an FTP server, listing the files and directories in the FTP server root directory using the dir() method, and then changing the directory using the cwd(path) method. In the example, the contents of the file Readme are downloaded from the FTP server and written to the local file readme.txt using the retrbinary(command, callback [, blocksize [, reset]]) method.

After you are finished downloading/managing the files on the FTP server, use the quit() method to close the connection.

import ftplib

#Open ftp connection
ftp = ftplib.FTP('ftp.novell.com', 'anonymous',

#List the files in the current directory
print "File List:"
files = ftp.dir()
print files

#Get the readme file
gFile = open("readme.txt", "wb")
ftp.retrbinary('RETR Readme', gFile.write)

#Print the readme file contents
print "\nReadme File Output:"
gFile = open("readme.txt", "r")
buff = gFile.read()
print buff


File List:
-rw-r-r- 1 root root  720 Dec 15  2005 README.html
-rw-r-r- 1 root root  1406 Dec 15  2005 Readme
drwxrwxrwx 2 root root  53248 Jun 26 18:10 incoming
drwxrwxrwx 2 root root  16384 Jun 26 17:53 outgoing
drwxr-xr-x 3 root root  4096 May 12 16:12 partners
drwxr-xr-x 2 root root  4096 Apr  4 18:24 priv
drwxr-xr-x 4 root root  4096 May 25 22:20 pub

Readme File Output:

 Before you download any software product you must
 read and agree to the following:
. . .

Output from ftp_client.py code

  • + Share This
  • 🔖 Save To Your Account