from os path import exists socket-based ftp tools file existence test def getfile(filesitediruser=()*verbose=truerefetch=false)""fetch file by ftp from site/directory anonymous or real loginbinary transfer ""if exists(fileand not refetchif verboseprint(file'already fetched'elseif verboseprint('downloading'filelocal open(file'wb'local file of same name tryremote ftp(siteconnect to ftp site remote login(*useranonymous=(or (namepswdremote cwd(dirremote retrbinary('retr filelocal write remote quit(finallylocal close(close file no matter what if verboseprint('download done 'caller handles exceptions if __name__ ='__main__'from getpass import getpass file 'monkeys jpgdir site 'ftp rmi netuser ('lutz'getpass('pswd?')getfile(filesitediruserthis module is mostly just repackaging of the ftp code we used to fetch the image file earlierto make it simpler and reusable because it is callable functionthe exported getfile getfile here tries to be as robust and generally useful as possiblebut even function this small implies some design decisions here are few usage notesftp mode the getfile function in this script runs in anonymous ftp mode by defaultbut two-item tuple containing username and password string may be passed to the user argument in order to log in to the remote server in nonanonymous mode to use anonymous ftpeither don' pass the user argument or pass it an empty tuple(the ftp object login method allows two optional arguments to denote username and passwordand the function(*argscall syntax in example - sends it whatever argument tuple you pass to user as individual arguments processing modes if passedthe last two arguments (verboserefetchallow us to turn off status messages printed to the stdout stream (perhaps undesirable in gui contextand to force downloads to happen even if the file already exists locally (the download overwrites the existing local file client-side scripting