"""
if verbose: print('Uploading', file)
local = open(file, 'rb') # local file of same name
remote = ftplib.FTP(site) # connect to FTP site
remote.login(*user) # anonymous or real login
remote.cwd(dir)
remote.storbinary('STOR ' + file, local, 1024)
remote.quit()
local.close()
if verbose: print('Upload done.')
if name == 'main':
site = 'ftp.rmi.net'
dir = '.'
import sys, getpass
pswd = getpass.getpass(site + ' pswd?') # filename on cmdline
putfile(sys.argv[1], site, dir, user=('lutz', pswd)) # nonanonymous login
Notice that for portability, the local file is opened in rb binary input mode this time to
suppress automatic line-feed character conversions. If this is binary information, we
don’t want any bytes that happen to have the value of the \r carriage-return character
to mysteriously go away during the transfer when run on a Windows client. We also
want to suppress Unicode encodings for nontext files, and we want reads to produce
the bytes strings expected by the storbinary upload operation (more on input file
modes later).
This script uploads a file you name on the command line as a self-test, but you will
normally pass in real remote filename, site name, and directory name strings. Also like
the download utility, you may pass a (username, password) tuple to the user argument
to trigger nonanonymous FTP mode (anonymous FTP is the default).
Playing the Monty Python theme song
It’s time for a bit of fun. To test, let’s use these scripts to transfer a copy of the Monty
Python theme song audio file I have at my website. First, let’s write a module that
downloads and plays the sample file, as shown in Example 13-6.
Example 13-6. PP4E\Internet\Ftp\sousa.py
#!/usr/local/bin/python
"""
Usage: sousa.py. Fetch and play the Monty Python theme song.
This will not work on your system as is: it requires a machine with Internet access
and an FTP server account you can access, and uses audio filters on Unix and your
.au player on Windows. Configure this and playfile.py as needed for your platform.
"""
from getpass import getpass
from PP4E.Internet.Ftp.getfile import getfile
from PP4E.System.Media.playfile import playfile
file = 'sousa.au' # default file coordinates
Transferring Files with ftplib | 865