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

yipeiwu_com6年前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()

相关文章

django批量导入xml数据

django后台批量导入数据 在生产环境中,往往数据不是几条或者几百条,那么举个例子,将公司所有员工员工号或者帐号密码导入进后台,那就不建议你去后台一条条记录去添加了 如何从xml中批...

Windows中安装使用Virtualenv来创建独立Python环境

Windows中安装使用Virtualenv来创建独立Python环境

0、什么时候会用到virtualenv? 假设系统中的两个应用,其中A应用对库LibFoo的版本要求为1,而B应用对同一个库LibFoo的版本要求为2,两个应用对同一个库的要求想冲突了,...

python开发环境PyScripter中文乱码问题解决方案

PyScripter看起来还是挺不错的一个python ide 环境: PyScripter 2.6.0.0 python3.4 问题: PyScripter有个小坑,打开文件后中文都成...

Python中字符串的常见操作技巧总结

本文实例总结了Python中字符串的常见操作技巧。分享给大家供大家参考,具体如下: 反转一个字符串 >>> S = 'abcdefghijklmnop' >&...

python3中函数参数的四种简单用法

下面给大家介绍python3中函数参数的四种简单用法,具体内容如下所示: def print_two(*args): arg1, arg2 = args print "arg...