1. Home
  2. Computing & Technology
  3. Python

Building an FTP Client in Python

From Al Lukaszewski, for About.com

5 of 6

Plain Text FTP Storage and Retrieval

What you do next will depend on the reason you are opening the FTP connection. The ftplib module provides for both storage and retrieval in both binary and plain text formats.

The methods for plain text transactions are as follows:

  • x.storlines(command, file) : used to store a file in line mode.
  • x.retrlines(command, callback) : used to retrieve a file in line mode.

For each method, a minimum of two arguments must be passed. Each requires an explicit declaration of the command you want to execute.

For storage, the common command is 'STOR' with the filename. For retrieval, the common command is 'RETR' and the filename. You should note that these are the common commands. They are not the only ones used, so you should verify which commands are supported by the server in question.

The second part of each command is the filename in question. For programming, it is therefore common to see variable command construction as follows:

ftp.storlines('STOR %s' %filename, filecontents)

You can, of course, hardwire the variables, but that would be at the cost of code flexibility.

The second argument of each method depends on what you are doing. For storage, as intimated above, the second argument is the file object itself.

For retrieval, include a callback, the function to be invoked when the file is retrieved. Here it is understood that you have created a file object for the remote file.

As the argument of the function is understood, no parentheses are necessary. An example of file retrieval in line mode is:

myfile = open('sometext.txt', 'wb')
ftp.retrlines('RETR %s' %filename, myfile.write)

Explore Python
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Python

©2009 About.com, a part of The New York Times Company.

All rights reserved.