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

yipeiwu_com5年前Python基础

访问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()

相关文章

python操作mongodb根据_id查询数据的实现方法

本文实例讲述了python操作mongodb根据_id查询数据的实现方法。分享给大家供大家参考。具体分析如下: _id是mongodb自动生成的id,其类型为ObjectId,所以如果需...

Linux下Pycharm、Anaconda环境配置及使用踩坑

Linux下Pycharm、Anaconda环境配置及使用踩坑

配置环境花了我一下午的时间,简单记录一下,希望能帮到一些新手。 1、下载PyCharm:https://www.jetbrains.com/pycharm/download/ 下载完成后...

Python基于动态规划算法计算单词距离

本文实例讲述了Python基于动态规划算法计算单词距离。分享给大家供大家参考。具体如下: #!/usr/bin/env python #coding=utf-8 def word_d...

Python3实现将本地JSON大数据文件写入MySQL数据库的方法

本文实例讲述了Python3实现将本地JSON大数据文件写入MySQL数据库的方法。分享给大家供大家参考,具体如下: 最近导师给了一个yelp上的评论数据,数据量达到3.55个G,如果进...

Python pyinotify模块实现对文档的实时监控功能方法

0x01 安装pyinotify >>> pip install pyinotify >>> import pyinotify 0x02 实现对...