This ftplib string processing worked with text-mode files in Python 2.X, but only
because there was no separate bytes type; \n was expanded to \r\n. Opening the
local file in binary mode for ftplib to read also means no Unicode decoding will
occur: the text is sent over sockets as a byte string in already encoded form. All of
which is, of course, a prime lesson on the impacts of Unicode encodings; consult
the module ftplib.py in the Python source library directory for more details.
For binary mode transfers, things are simpler—we open the local file in rb binary
mode to suppress Unicode decoding and automatic mapping everywhere, and re-
turn the bytes strings expected by ftplib on read. Binary data is not Unicode text,
and we don’t want bytes in an audio file that happen to have the same value as
\r to magically disappear when read on Windows.
As for the mirror download script, this program simply iterates over all files to be
transferred (files in the local directory listing this time), and transfers each in turn—in
either text or binary mode, depending on the files’ names. Here is the command I use
to upload my entire website from my laptop Windows PC to a remote Linux server at
my ISP, in a single step:
C:\...\PP4E\Internet\Ftp\Mirror> uploadflat.py test
Password for lutz on learning-python.com:
Clean remote directory first? y
connecting...
deleting remote.
cannot delete remote.
deleting remote ..
cannot delete remote ..
deleting remote 2004-longmont-classes.html
deleting remote 2005-longmont-classes.html
deleting remote 2006-longmont-classes.html
deleting remote about-lp1e.html
deleting remote about-lp2e.html
deleting remote about-lp3e.html
deleting remote about-lp4e.html
...lines omitted...
uploading test\2004-longmont-classes.html to 2004-longmont-classes.html as text
uploading test\2005-longmont-classes.html to 2005-longmont-classes.html as text
uploading test\2006-longmont-classes.html to 2006-longmont-classes.html as text
uploading test\about-lp1e.html to about-lp1e.html as text
uploading test\about-lp2e.html to about-lp2e.html as text
uploading test\about-lp3e.html to about-lp3e.html as text
uploading test\about-lp4e.html to about-lp4e.html as text
uploading test\about-pp-japan.html to about-pp-japan.html as text
...lines omitted...
uploading test\whatsnew.html to whatsnew.html as text
uploading test\whatsold.html to whatsold.html as text
uploading test\wxPython.doc.tgz to wxPython.doc.tgz as application gzip
uploading test\xlate-lp.html to xlate-lp.html as text
Transferring Directories with ftplib | 883