The ftplib Module
The ftplib
module contains a File Transfer Protocol
(FTP) client implementation.
Example 7-22 demonstrates how to log in and get a directory listing of the login directory. Note that the format of the directory listing is server dependent (it’s usually the same as the format used by the directory listing utility on the server host platform).
Example 7-22. Using the ftplib Module to Get a Directory Listing
File: ftplib-example-1.py import ftplib ftp = ftplib.FTP("www.python.org") ftp.login("anonymous", "ftplib-example-1") print ftp.dir() ftp.quit()total 34
drwxrwxr-x 11 root 4127 512 Sep 14 14:18 .
drwxrwxr-x 11 root 4127 512 Sep 14 14:18 ..
drwxrwxr-x 2 root 4127 512 Sep 13 15:18 RCS
lrwxrwxrwx 1 root bin 11 Jun 29 14:34 README -> welcome.msg
drwxr-xr-x 3 root wheel 512 May 19 1998 bin
drwxr-sr-x 3 root 1400 512 Jun 9 1997 dev
drwxrwxr-- 2 root 4127 512 Feb 8 1998 dup
drwxr-xr-x 3 root wheel 512 May 19 1998 etc
...
Downloading files is easy; just use the appropriate
retr
function. Note that when you download a
text file, you have to add line endings yourself. The
function in Example 7-23 uses a lambda
expression to do that on the
fly.
Example 7-23. Using the ftplib Module to Retrieve Files
File: ftplib-example-2.py import ftplib import sys def gettext(ftp, filename, outfile=None): # fetch a text file if outfile is None: outfile = sys.stdout # use a lambda to add newlines to the lines read from the server ftp.retrlines("RETR " + filename, lambda s, w=outfile.write: ...
Get Python Standard Library now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.