Being an FTP Client
Credit: Luther Blissett
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.
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'))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, ...