[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

localfile = open(localpath, 'rb')
self.connection.storlines('STOR ' + remotename, localfile)
else:
localfile = open(localpath, 'rb')
self.connection.storbinary('STOR ' + remotename, localfile)
localfile.close()


def downloadDir(self):
"""
download all files from remote site/dir per config
ftp nlst() gives files list, dir() gives full details
"""
remotefiles = self.connection.nlst() # nlst is remote listing
for remotename in remotefiles:
if remotename in ('.', '..'): continue
localpath = os.path.join(self.localdir, remotename)
print('downloading', remotename, 'to', localpath, 'as', end=' ')
self.downloadOne(remotename, localpath)
print('Done:', len(remotefiles), 'files downloaded.')


def uploadDir(self):
"""
upload all files to remote site/dir per config
listdir() strips dir path, any failure ends script
"""
localfiles = os.listdir(self.localdir) # listdir is local listing
for localname in localfiles:
localpath = os.path.join(self.localdir, localname)
print('uploading', localpath, 'to', localname, 'as', end=' ')
self.uploadOne(localname, localpath, localname)
print('Done:', len(localfiles), 'files uploaded.')


def run(self, cleanTarget=lambda:None, transferAct=lambda:None):
"""
run a complete FTP session
default clean and transfer are no-ops
don't delete if can't connect to server
"""
self.connectFtp()
cleanTarget()
transferAct()
self.connection.quit()


if name == 'main':
ftp = FtpTools()
xfermode = 'download'
if len(sys.argv) > 1:
xfermode = sys.argv.pop(1) # get+del 2nd arg
if xfermode == 'download':
ftp.configTransfer()
ftp.run(cleanTarget=ftp.cleanLocals, transferAct=ftp.downloadDir)
elif xfermode == 'upload':
ftp.configTransfer(site='learning-python.com', rdir='books', user='lutz')
ftp.run(cleanTarget=ftp.cleanRemotes, transferAct=ftp.uploadDir)


Transferring Directories with ftplib | 891
Free download pdf