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的即时标记项目练习笔记
Sep 18 Python
Python下的twisted框架入门指引
Apr 15 Python
Python之Scrapy爬虫框架安装及简单使用详解
Dec 22 Python
对Python协程之异步同步的区别详解
Feb 19 Python
基于Python的微信机器人开发 微信登录和获取好友列表实现解析
Aug 21 Python
通过python扫描二维码/条形码并打印数据
Nov 14 Python
基于numpy中的expand_dims函数用法
Dec 18 Python
pycharm下配置pyqt5的教程(anaconda虚拟环境下+tensorflow)
Mar 25 Python
tensorflow指定CPU与GPU运算的方法实现
Apr 21 Python
浅谈opencv自动光学检测、目标分割和检测(连通区域和findContours)
Jun 04 Python
在python中list作函数形参,防止被实参修改的实现方法
Jun 05 Python
pandas针对excel处理的实现
Jan 15 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 session
2013/10/28 PHP
php实现根据词频生成tag云的方法
2015/04/17 PHP
分享PHP-pcntl 实现多进程代码
2016/09/30 PHP
在 Laravel 中动态隐藏 API 字段的方法
2019/10/25 PHP
JavaScript运行时库属性一览表
2014/03/14 Javascript
jQuery设置和获取HTML、文本和值示例
2014/07/08 Javascript
点击标签切换和自动切换DIV选项卡
2014/08/10 Javascript
javascript事件冒泡实例分析
2015/05/13 Javascript
简介EasyUI datagrid editor combogrid搜索框的实现
2016/04/01 Javascript
基于JS实现textarea中获取动态剩余字数的方法
2016/05/25 Javascript
Javascript实现跑马灯效果的简单实例
2016/05/31 Javascript
js点击按钮实现水波纹效果代码(CSS3和Canves)
2016/09/15 Javascript
js面向对象实现canvas制作彩虹球喷枪效果
2016/09/24 Javascript
javascript匀速动画和缓冲动画详解
2016/10/20 Javascript
微信小程序之小豆瓣图书实例
2016/11/30 Javascript
jQuery ajax实现省市县三级联动
2021/03/07 Javascript
js学习心得_一个简单的动画库封装tween.js
2017/07/14 Javascript
JS对象与JSON互转换、New Function()、 forEach()、DOM事件流等js开发基础小结
2017/08/10 Javascript
vue 自定义指令自动获取文本框焦点的方法
2018/08/25 Javascript
Python strip lstrip rstrip使用方法
2008/09/06 Python
python创建只读属性对象的方法(ReadOnlyObject)
2013/02/10 Python
python进阶教程之模块(module)介绍
2014/08/30 Python
常用python编程模板汇总
2016/02/12 Python
Python简单网络编程示例【客户端与服务端】
2017/05/26 Python
python实现mysql的读写分离及负载均衡
2018/02/04 Python
Python wxPython库消息对话框MessageDialog用法示例
2018/09/03 Python
python聚类算法解决方案(rest接口/mpp数据库/json数据/下载图片及数据)
2019/08/28 Python
keras获得model中某一层的某一个Tensor的输出维度教程
2020/01/24 Python
Python基础之字符串操作常用函数集合
2020/02/09 Python
Python 在函数上添加包装器
2020/07/28 Python
GUESS西班牙官方网上商城:美国服饰品牌
2017/03/15 全球购物
请用Python写一个获取用户输入数字,并根据数字大小输出不同信息的脚本
2014/05/20 面试题
土地转让协议书
2014/09/27 职场文书
2014年教研工作总结
2014/12/06 职场文书
酒店保洁员岗位职责
2015/02/26 职场文书
Ajax请求超时与网络异常处理图文详解
2021/05/23 Javascript