passive ftp by default remotesite 'learning-python comupload to this site remotedir 'booksfrom machine running on remoteuser 'lutzremotepass getpass('password for % on % (remoteuserremotesite)localdir (len(sys argv and sys argv[ ]or cleanall input('clean remote directory first')[: in [' '' 'print('connecting 'connection ftplib ftp(remotesiteconnection login(remoteuserremotepassconnection cwd(remotedirif nonpassiveconnection set_pasv(falseconnect to ftp site log in as user/password cd to directory to copy force active mode ftp most servers do passive if cleanallfor remotename in connection nlst()try to delete all remotes tryfirstto remove old files print('deleting remote'remotenameconnection delete(remotenameskips and if attempted exceptprint('cannot delete remote'remotenamecount localfiles os listdir(localdirfor localname in localfilesmimetypeencoding guess_type(localnamemimetype mimetype or '?/?maintype mimetype split('/')[ upload all local files listdir(strips dir path any failure ends script ('text/plain''gzip'may be (nonenonejpg ('image/jpeg'none'localpath os path join(localdirlocalnameprint('uploading'localpath'to'localnameend='print('as'maintypeencoding or ''if maintype ='textand encoding =noneuse ascii mode xfer and bytes file need rb mode for ftplib' crlf logic localfile open(localpath'rb'connection storlines('stor localnamelocalfileelseuse binary mode xfer and bytes file localfile open(localpath'rb'connection storbinary('stor localnamelocalfilelocalfile close(count + connection quit(print('done:'count'files uploaded 'transferring directories with ftplib