10.8 Being an FTP Client


Credit: Luther Blissett

10.8.1 Problem

You want to connect to an FTP server and upload or retrieve files. You might want to automate the one-time transfer of many files or automatically mirror an entire section of an FTP server.

10.8.2 Solution

The ftplib module makes this reasonably easy:

import ftplib ftp = ftplib.FTP("ftp.host.com") ftp.login(username, password) ftp.cwd(directory) # Retrieve a binary file to save on your disk ftp.retrbinary('RETR '+filename, open(filename,'wb').write) # Upload a binary file from your disk ftp.storbinary('STOR '+filename, open(filename,'rb'))

10.8.3 Discussion

urllib may be sufficient for getting documents via FTP, but the ftplib module offers more functionality (including the ability to use FTP to upload files, assuming, of course, that you have the needed permission on the server in question) and finer-grained control for this specific task.

login defaults to an anonymous login attempt if you call it without arguments, but you normally pass username and password arguments. cwd changes the current directory on the server. retrbinary retrieves binary data from the server and repeatedly calls its second argument with the data. Thus, you will usually pass a file object's write bound method as the second argument. storbinary stores binary data on the server, taking the data from its second argument, which must be a file-like object (the method calls read(N) on it). There are also the retrlines and storlines methods, which work similarly but on text data, line by line.

Functions and methods in the ftplib module may raise exceptions of many classes to diagnose possible errors. To catch them all, you can use ftplib.all_errors, which is the tuple of all possible exception classes:

try: ftp = ftplib.FTP("ftp.host.com") except ftp.all_errors, error:     print "Cannot connect:", error else:     try: ftp.login(username, password)     except ftp.all_errors, error:         print "Cannot login:", error     else:         ...

10.8.4 See Also

Documentation for the standard library module ftplib in the Library Reference.



Python Cookbook
Python Cookbook
ISBN: 0596007973
EAN: 2147483647
Year: 2005
Pages: 346

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net