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读写文件操作示例程序
Dec 02 Python
python对指定目录下文件进行批量重命名的方法
Apr 18 Python
python八大排序算法速度实例对比
Dec 06 Python
Python标准库笔记struct模块的使用
Feb 22 Python
numpy给array增加维度np.newaxis的实例
Nov 01 Python
python实现字符串完美拆分split()的方法
Jul 16 Python
Python装饰器原理与基本用法分析
Jan 07 Python
使用Python文件读写,自定义分隔符(custom delimiter)
Jul 05 Python
python实现人性化显示金额数字实例详解
Sep 25 Python
python opencv角点检测连线功能的实现代码
Nov 24 Python
Python基础之变量的相关知识总结
Jun 23 Python
python blinker 信号库
May 04 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+AJAX聊天程序[聊天室]提供下载
2007/07/21 PHP
PHP判断是否为空的几个函数对比
2015/04/21 PHP
PHP实现连接设备、通讯和发送命令的方法
2015/10/13 PHP
php PDO实现的事务回滚示例
2017/03/23 PHP
jquery中常用的SET和GET
2009/01/13 Javascript
传智播客学习之JavaScript基础篇
2009/11/13 Javascript
js parseInt("08")未指定进位制问题
2010/06/19 Javascript
Javascript 按位左移运算符使用介绍(
2014/02/04 Javascript
基于jQuery的Web上传插件Uploadify使用示例
2016/05/19 Javascript
js本地图片预览实现代码
2016/10/09 Javascript
AngularJS封装指令方法详解
2016/12/12 Javascript
jQuery选择器中的特殊符号处理方法
2017/09/08 jQuery
解决在vue+webpack开发中出现两个或多个菜单公用一个组件问题
2017/11/28 Javascript
vue本地打开build后生成的dist文件夹index.html问题
2019/09/04 Javascript
微信小程序实现导航栏和内容上下联动功能代码
2020/06/29 Javascript
结合axios对项目中的api请求进行封装操作
2020/09/21 Javascript
[00:20]DOTA2荣耀之路7:-ah fu-抢盾
2018/05/31 DOTA
[01:02:00]DOTA2-DPC中国联赛 正赛 Elephant vs IG BO3 第三场 1月24日
2021/03/11 DOTA
python下setuptools的安装详解及No module named setuptools的解决方法
2017/07/06 Python
详解python中的数据类型和控制流
2019/08/08 Python
python函数参数(必须参数、可变参数、关键字参数)
2019/08/16 Python
Django框架 信号调度原理解析
2019/09/04 Python
使用tensorboard可视化loss和acc的实例
2020/01/21 Python
sklearn+python:线性回归案例
2020/02/24 Python
Pycharm 使用 Pipenv 新建的虚拟环境(图文详解)
2020/04/16 Python
翻转数列python实现,求前n项和,并能输出整个数列的案例
2020/05/03 Python
Python数据可视化图实现过程详解
2020/06/12 Python
canvas学习笔记之2d画布基础的实现
2019/02/21 HTML / CSS
戴尔马来西亚官网:Dell Malaysia
2020/05/02 全球购物
家长会演讲稿范文
2014/01/10 职场文书
客户服务经理岗位职责
2014/01/29 职场文书
《巨人的花园》教学反思
2014/02/12 职场文书
公司接待方案
2014/03/08 职场文书
小学学习委员竞选稿
2015/11/20 职场文书
新学期新寄语,献给新生们!
2019/11/15 职场文书
一文带你探究MySQL中的NULL
2021/11/11 MySQL