Python FTP两个文件夹间的同步实例代码


Posted in Python onMay 25, 2018

具体代码如下所示:

# -*- coding: utf-8 -*- 
''''''' 
  ftp自动检测源文件夹的更新,将源文件夹更新的内容拷贝到目标文件夹中 
  使用树的层序遍历算法,支持深度目录拷贝 
''' 
import os 
from ftplib import FTP 
import os,sys,string,datetime,time 
import shutil 
import socket 
class MyUpdateMonitor(object): 
  def __init__(self, hostaddr, username, password, remotedir_old, remotedir_new, port = 21): 
    self.hostaddr = hostaddr 
    self.username = username 
    self.password = password 
    self.remotedir_old = remotedir_old 
    self.remotedir_new = remotedir_new 
    # self.port = port 
    self.ftp = FTP() 
    # 源文件文件队列 
    self.FolderListOld = [] 
    # 目标文件文件队列 
    self.FolderListNew = [] 
  def __del__(self): 
    self.ftp.close() 
    self.FolderListOld.clear() 
    self.FolderListNew.clear() 
  def FtpLogin(self): 
    ftp = self.ftp 
    try: 
      timeout = 300 
      socket.setdefaulttimeout(timeout) 
      ftp.set_pasv(True) 
      print u'开始连接到 %s' %(hostaddr) 
      ftp.connect(hostaddr) 
      print u'成功连接到 %s' %(hostaddr) 
      print u'开始登录到 %s' %(hostaddr) 
      ftp.login(username, password) 
      print u'成功登录到 %s' %(hostaddr) 
      ftp.getwelcome() 
    except Exception, e: 
      print 'find exception now:',e 
  # 使用树的层序遍历来检查文件目录 
  def LevelOrderFolder(self): 
    # 新增文件起始位置和终止位置 
    start = 0 
    end = 0 
    try: 
      # 将根目录放入队列中 
      self.FolderListOld.append(self.remotedir_old) 
      self.FolderListNew.append(self.remotedir_new) 
      while not (0 == len(self.FolderListOld)): 
        end = start 
        # 将文件夹下的文件全部压入队列 
        if os.path.isdir(self.FolderListOld[0]): 
          files = os.listdir(self.FolderListOld[0]) 
          for file in files: 
            self.FolderListOld.append(os.path.join(self.FolderListOld[0], file)) 
          # 确定新增文件在队列中的位置 
          end += len(files) 
        # 将已经查看的文件夹删除 
        del self.FolderListOld[0] 
        # 检查目标文件夹该级目录 
        if os.path.isdir(self.FolderListNew[0]): 
          # 将该级目录的文件都列出 
          files = os.listdir(self.FolderListNew[0]) 
          # 检查源文件该级目录下的文件在目标该级目录下是否有 
          for file in self.FolderListOld[start:end]: 
            temp = file.split('\\') 
            if temp[-1] in files: 
              # 这里判断文件大小是否一致,不一致拷过去 
              if os.path.isfile(file) and not os.path.getsize(file) == os.path.getsize(os.path.join(self.FolderListNew[0], temp[-1])): 
                print 'Find the file(%s) size is changed!\n' % file 
                # print r'Start delete...\n' 
                # os.remove(os.path.join(self.FolderListNew[0], temp[-1])) 
                # print r'delete is over...\n' 
                print 'Start Copy...\n' 
                shutil.copyfile(file, os.path.join(self.FolderListNew[0], temp[-1])) 
                print 'Copy is over...\n' 
              # # 如果是文件夹存在,但是修改过,没有必要全部拷贝文件夹,可以到文件夹中拷贝单个文件 
              # if os.path.isfile(file) and not (os.path.getmtime(file) == os.path.getmtime(os.path.join(self.FolderListNew[0], temp[-1]))): 
              #   print 'Find the file(%s) size is changed!\n' % file 
              #   changetime = os.path.getmtime(file) #以毫秒为单位的时间,自1970年开始到现今 
              #   changetime = float(changetime) 
              #   print 'Change Time is', time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(changetime)), r'\n' 
              # 
              #   print 'Start Copy...\n' 
              #   shutil.copyfile(file, os.path.join(self.FolderListNew[0], temp[-1])) 
              #   print 'Copy is over...\n' 
            else: 
              if os.path.isdir(file): 
                # 如果是文件夹不存在使用,目录树拷贝 
                print 'Find the folder(%s) is updated!\n' % file 
                print 'Start Copy...\n' 
                shutil.copytree(file, os.path.join(self.FolderListNew[0], temp[-1])) 
                print 'Copy is over...\n' 
              else: 
                # 如果是文件 
                print 'Find the file(%s) is updated!\n' % file 
                print 'Start Copy...\n' 
                shutil.copyfile(file, os.path.join(self.FolderListNew[0], temp[-1])) 
                print 'Copy is over...\n' 
            self.FolderListNew.append(os.path.join(self.FolderListNew[0], temp[-1])) 
        del self.FolderListNew[0] 
        start = end - 1 
    except Exception, e: 
      print 'find exception now:',e 
if __name__ == '__main__': 
  # 配置如下变量 
  hostaddr = r'10.204.16.28' # ftp地址 
  username = r' ' # 用户名 
  password = r' ' # 密码 
  remotedir_old = r'\\10.204.16.28\Home\TDME\Test\Old\TMUMH_1.6.1055' 
  remotedir_new = r'\\10.204.16.28\Home\TDME\Test\New\TMUMH_1.6.1055' 
  monitorfileupdae = MyUpdateMonitor(hostaddr, username, password, remotedir_old, remotedir_new) 
  monitorfileupdae.FtpLogin() 
  while True: 
    print 'Start Check Update...\n' 
    monitorfileupdae.LevelOrderFolder() 
    print 'Check Update is Over...\tSleep one hour...' 
    time.sleep(3600) 
  print 'hello'

总结

以上所述是小编给大家介绍的Python FTP两个文件夹间的同步实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

Python 相关文章推荐
python使用内存zipfile对象在内存中打包文件示例
Apr 30 Python
python删除列表内容
Aug 04 Python
python用模块zlib压缩与解压字符串和文件的方法
Dec 16 Python
python3实现ftp服务功能(客户端)
Mar 24 Python
centos6.8安装python3.7无法import _ssl的解决方法
Sep 17 Python
删除DataFrame中值全为NaN或者包含有NaN的列或行方法
Nov 06 Python
Windows 安装 Anaconda3+PyCharm的方法步骤
Jun 13 Python
Python 异常处理Ⅳ过程图解
Oct 18 Python
使用matplotlib动态刷新指定曲线实例
Apr 23 Python
详解pyinstaller生成exe的闪退问题解决方案
Jun 19 Python
虚拟机下载python是否需要联网
Jul 27 Python
python跨文件使用全局变量的实现
Nov 17 Python
Python单元测试实例详解
May 25 #Python
python 请求服务器的实现代码(http请求和https请求)
May 25 #Python
django将图片上传数据库后在前端显式的方法
May 25 #Python
python3.6.3+opencv3.3.0实现动态人脸捕获
May 25 #Python
Django1.9 加载通过ImageField上传的图片方法
May 25 #Python
python matplotlib 在指定的两个点之间连线方法
May 25 #Python
基于python OpenCV实现动态人脸检测
May 25 #Python
You might like
php计划任务之验证是否有多个进程调用同一个job的方法
2015/12/07 PHP
php无法连接mysql数据库的正确解决方法
2016/07/01 PHP
Smarty模板常见的简单应用分析
2016/11/15 PHP
PHP用正则匹配form表单中所有元素的类型和属性值实例代码
2017/02/28 PHP
php获取是星期几的的一些常用姿势
2019/12/15 PHP
Prototype RegExp对象 学习
2009/07/19 Javascript
JS 用6N±1法求素数 实例教程
2009/10/20 Javascript
javascript 动态设置已知select的option的value值的代码
2009/12/16 Javascript
picChange 图片切换特效的函数代码
2010/05/06 Javascript
jquery 无限级联菜单案例分享
2013/03/26 Javascript
在jQuery中 关于json空对象筛选替换
2013/04/15 Javascript
下拉菜单点击实现连接跳转功能的js代码
2013/05/19 Javascript
jQuery点击自身以外地方关闭弹出层的简单实例
2013/12/24 Javascript
使用documentElement正确取得当前可见区域的大小
2014/07/25 Javascript
JQuery.get提交页面不跳转的解决方法
2015/01/13 Javascript
Bootstrap Navbar Component实现响应式导航
2016/10/08 Javascript
微信小程序 实现拖拽事件监听实例详解
2016/11/16 Javascript
jQuery按需加载轮播图(web前端性能优化)
2017/02/17 Javascript
vue.js利用defineProperty实现数据的双向绑定
2017/04/28 Javascript
JavaScript中附件预览功能实现详解(推荐)
2017/08/15 Javascript
详解vue的双向绑定原理及实现
2019/05/05 Javascript
vue.js实现只能输入数字的输入框
2019/10/19 Javascript
Python学习之Django的管理界面代码示例
2018/02/10 Python
python 3.6.5 安装配置方法图文教程
2018/09/18 Python
在Django admin中编辑ManyToManyField的实现方法
2019/08/09 Python
python的pyecharts绘制各种图表详细(附代码)
2019/11/11 Python
将tensorflow.Variable中的某些元素取出组成一个新的矩阵示例
2020/01/04 Python
使用jupyter notebook将文件保存为Markdown,HTML等文件格式
2020/04/14 Python
python读取hdfs并返回dataframe教程
2020/06/05 Python
用纯CSS3实现网页中常见的小箭头
2017/10/16 HTML / CSS
顶撞领导检讨书
2014/01/29 职场文书
网吧七夕活动策划方案
2014/08/31 职场文书
四风问题个人对照检查材料
2014/09/26 职场文书
银行自荐信怎么写
2015/03/05 职场文书
工程质检员岗位职责
2015/04/08 职场文书
母婴行业实体、电商模式全面解析
2019/08/01 职场文书