print('downloading'remotename'to'localpathend='print('as'maintypeencoding or ''if maintype ='textand encoding =noneuse ascii mode xfer and text file use encoding compatible wth ftplib' localfile open(localpath' 'encoding=connection encodingcallback lambda linelocalfile write(line '\ 'connection retrlines('retr remotenamecallbackelseuse binary mode xfer and bytes file localfile open(localpath'wb'connection retrbinary('retr remotenamelocalfile writelocalfile close(count + connection quit(print('done:'count'files downloaded 'there' not much that is new to speak of in this scriptcompared to other ftp examples we've seen thus far we open connection with the remote ftp serverlog in with username and password for the desired account (this script never uses anonymous ftp)and go to the desired remote directory new herethoughare loops to iterate over all the files in local and remote directoriestext-based retrievalsand file deletionsdeleting all local files this script has cleanall optionenabled by an interactive prompt if selectedthe script first deletes all the files in the local directory before downloadingto make sure there are no extra files that aren' also on the server (there may be junk here from prior downloadto delete local filesthe script calls os listdir to get list of filenames in the directoryand os remove to delete eachsee (or the python library manualfor more details if you've forgotten what these calls do notice the use of os path join to concatenate directory path and filename according to the host platform' conventionsos listdir returns filenames without their directory pathsand this script is not necessarily run in the local directory where downloads will be placed the local directory defaults to the current directory (")but can be set differently with command-line argument to the script fetching all remote files to grab all the files in remote directorywe first need list of their names the ftp object' nlst method is the remote equivalent of os listdirnlst returns list of the string names of all files in the current remote directory once we have this listwe simply step through it in looprunning ftp retrieval commands for each filename in turn (more on this in minutethe nlst method ismore or lesslike requesting directory listing with an ls command in typical interactive ftp programsbut python automatically splits up client-side scripting