as we saw in Chapter 4, this happens automatically on Windows when writing files
opened in w text mode. We also want to avoid Unicode issues in Python 3.X—as we
also saw in Chapter 4, strings are encoded when written in text mode and this isn’t
appropriate for binary data such as images. A text-mode file would also not allow for
the bytes strings passed to write by the FTP library’s retrbinary in any event, so rb is
effectively required here (more on output file modes later).
Finally, we call the FTP quit method to break the connection with the server and man-
ually close the local file to force it to be complete before it is further processed (it’s not
impossible that parts of the file are still held in buffers before the close call):
connection.quit()
localfile.close()
And that’s all there is to it—all the FTP, socket, and networking details are hidden
behind the ftplib interface module. Here is this script in action on a Windows 7 ma-
chine; after the download, the image file pops up in a Windows picture viewer on my
laptop, as captured in Figure 13-1. Change the server and file assignments in this script
to test on your own, and be sure your PYTHONPATH environment variable includes the
PP4E root’s container, as we’re importing across directories on the examples tree here:
C:\...\PP4E\Internet\Ftp> python getone.py
Pswd?
Connecting...
Downloading...
Open file?y
Notice how the standard Python getpass.getpass is used to ask for an FTP password.
Like the input built-in function, this call prompts for and reads a line of text from the
console user; unlike input, getpass does not echo typed characters on the screen at all
(see the moreplus stream redirection example of Chapter 3 for related tools). This is
handy for protecting things like passwords from potentially prying eyes. Be careful,
though—after issuing a warning, the IDLE GUI echoes the password anyhow!
The main thing to notice is that this otherwise typical Python script fetches information
from an arbitrarily remote FTP site and machine. Given an Internet link, any informa-
tion published by an FTP server on the Net can be fetched by and incorporated into
Python scripts using interfaces such as these.
Using urllib to Download Files
In fact, FTP is just one way to transfer information across the Net, and there are more
general tools in the Python library to accomplish the prior script’s download. Perhaps
the most straightforward is the Python urllib.request module: given an Internet ad-
dress string—a URL, or Universal Resource Locator—this module opens a connection
to the specified server and returns a file-like object ready to be read with normal file
object method calls (e.g., read, readline).
Transferring Files with ftplib | 857