Python之FTP传输

    添加时间:2013-6-20 点击量:

    接见FTP,无非两件工作:upload和download,比来在项目中须要从ftp多量文件,然后我就试着去实验本身的ftp操纵类,如下(PS:此段有题目,别复制应用,可以参考去实验本身的ftp类!)



    
    
    Created on Jun 19, 2013

    @author: Berlin

    import os
    ftplib import FTP

    class FTPSync():
    def __init__(self, host, usr, psw, log_file):
    self.host
    = host
    self.usr
    = usr
    self.psw
    = psw
    self.log_file
    = log_file

    def __ConnectServer(self):
    try:
    self.ftp
    = FTP(self.host)
    self.ftp.login(self.usr, self.psw)
    self.ftp.set_pasv(False)
    return True
    except Exception:
    return False

    def __CloseServer(self):
    try:
    self.ftp.quit()
    return True
    except Exception:
    return False

    def __CheckSizeEqual(self, remoteFile, localFile):
    try:
    remoteFileSize
    = self.ftp.size(remoteFile)
    localFileSize
    = os.path.getsize(localFile)
    if localFileSize == remoteFileSize:
    return True
    else:
    return False
    except Exception:
    return None

    def __DownloadFile(self, remoteFile, localFile):
    try:
    self.ftp.cwd(os.path.dirname(remoteFile))
    f
    = open(localFile, wb
    remoteFileName
    = RETR + os.path.basename(remoteFile)
    self.ftp.retrbinary(remoteFileName, f.write)

    if self.__CheckSizeEqual(remoteFile, localFile):
    self.log_file.write(
    The File is downloaded successfully to %s + \n localFile)
    return True
    else:
    self.log_file.write(
    The localFile %s size is not same with the remoteFile + \n localFile)
    return False
    except Exception:
    return False

    def __DownloadFolder(self, remoteFolder, localFolder):
    try:
    fileList
    = []
    self.ftp.retrlines(
    NLST, fileList.append)
    for remoteFile in fileList:
    localFile
    = os.path.join(localFolder, remoteFile)
    return self.__DownloadFile(remoteFile, localFile)
    except Exception:
    return False

    def SyncFromFTP(self, remoteFolder, localFolder):
    self.__DownloadFolder(remoteFolder, localFolder)
    self.log_file.close()
    self.
    __CloseServer()


    还有题目存在,终极版本不在此共享!


    终极版本首要改进:多线程上传与功能!

    我俩之间有着强烈的吸引力。短短几个小时后,我俩已经明白:我们的心是一个整体的两半,我俩的心灵是孪生兄妹,是知己。她让我感到更有活力,更完美,更幸福。即使她不在我身边,我依然还是感到幸福,因为她总是以这样或者那样的方式出现在我心头。——恩里克·巴里奥斯《爱的文明》
    分享到: