编写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()

相关文章

分享Python字符串关键点

字符串是 Python 中最常用的数据类型。我们可以使用引号来创建字符串。python字符串关键点有下面几点: 1.一些引号分隔的字符 你可以把字符串看出是Python的一种数据类型...

python3 写一个WAV音频文件播放器的代码

环境:ubuntu 16.04 python3.5 pycharm 包 : wave pyaudio sys 上代码:AudioPlayer.py # coding:utf-8 #...

python的random模块及加权随机算法的python实现方法

random是用于生成随机数的,我们可以利用它随机生成数字或者选择字符串。 •random.seed(x)改变随机数生成器的种子seed。 一般不必特别去设定seed,Pyt...

Python函数嵌套实例

在Python中函数可以作为参数进行传递,而也可以赋值给其他变量(类似Javascript,或者C/C++中的函数指针); 类似Javascript,Python支持函数嵌套,Javas...

python绘制中国大陆人口热力图

python绘制中国大陆人口热力图

这篇文章给出了如何绘制中国人口密度图,但是运行存在一些问题,我在一些地方进行了修改。 本人使用的IDE是anaconda,因此事先在anaconda prompt 中安装Basemap包...