module is used in much the same way as
httplib module: a single class,
FTP, provides all of the functionality.
The FTP protocol supports a variety of commands, which include such operations as logging in, navigating the filesystem, and retrieving directory listings. Let’s create an FTP session:
>>> import ftplib >>> ftp = ftplib.FTP('ftp.python.org') # connect to host, default port >>>
Log on as an anonymous user:
>>> ftp.login('anonymous', 'firstname.lastname@example.org') "230-WELCOME to python.org, the Python programming language ..." >>>
Get a directory listing:
>>> ftp.retrlines('LIST') # list directory contents total 38 drwxrwxr-x 11 root 4127 512 Aug 28 20:23 . ... -r--r--r-- 1 klm 1000 764 Aug 25 19:32 welcome.msg '226 Transfer complete.'
Notice there’s a file welcome.msg:
let’s download the file. Open a local file and indicate its
write method should be called to store the data:
>>> file=open("welcome.msg", "w") >>> ftp.retrlines("retr welcome.msg", file.write) '226 Transfer complete.' >>> file.close()
Now reopen the file and print the data:
>>> open("welcome.msg", "r").read() "WELCOME to python.org, the Python programming language home site. ..." >>>
To retrieve a binary file (such as an executable), you could use the
; it takes the same methods as
, except it also allows you to specify a
block size for the transfer. In this case you should remember to open
the file itself in binary mode, as discussed in Chapter 3.