首页 编程教程正文

编写Python脚本来实现最简单的FTP下载的教程

piaodoo 编程教程 2020-02-02 12:20:48 1067 0 python教程

这篇文章主要介绍了编写Python脚本来实现最简单的FTP下载的教程,主要用到了ftplib模块,无图形界面...需要的朋友可以参考下

访问FTP,无非两件事情:upload和download,最近在项目中需要从ftp下载大量文件,然后我就试着去实验自己的ftp操作类,如下(PS:此段有问题,别复制使用,可以参考去试验自己的ftp类!)

import os
from 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()

版权声明:

本站所有资源均为站长或网友整理自互联网或站长购买自互联网,站长无法分辨资源版权出自何处,所以不承担任何版权以及其他问题带来的法律责任,如有侵权或者其他问题请联系站长删除!站长QQ754403226 谢谢。

有关影视版权:本站只供百度云网盘资源,版权均属于影片公司所有,请在下载后24小时删除,切勿用于商业用途。本站所有资源信息均从互联网搜索而来,本站不对显示的内容承担责任,如您认为本站页面信息侵犯了您的权益,请附上版权证明邮件告知【754403226@qq.com】,在收到邮件后72小时内删除。本文链接:https://www.piaodoo.com/987.html

搜索