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 相关文章推荐
selenium+python实现自动登录脚本
Apr 22 Python
Django之Mode的外键自关联和引用未定义的Model方法
Dec 15 Python
python使用xlrd模块读取xlsx文件中的ip方法
Jan 11 Python
用python一行代码得到数组中某个元素的个数方法
Jan 28 Python
python三方库之requests的快速上手
Mar 04 Python
Django框架使用内置方法实现登录功能详解
Jun 12 Python
3种python调用其他脚本的方法
Jan 06 Python
Python进程的通信Queue、Pipe实例分析
Mar 30 Python
python传到前端的数据,双引号被转义的问题
Apr 03 Python
keras之权重初始化方式
May 21 Python
Python tempfile模块生成临时文件和临时目录
Sep 30 Python
详解Java中一维、二维数组在内存中的结构
Feb 11 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,js双版本
2012/09/25 PHP
php根据分类合并数组的方法实例详解
2013/11/06 PHP
PHP之正则表达式捕获组与非捕获组(详解)
2015/07/29 PHP
jQuery循环滚动展示代码 可应用到文字和图片上
2012/05/11 Javascript
解析javascript 数组以及json元素的添加删除
2013/06/26 Javascript
利用JQuery和Servlet实现跨域提交请求示例分享
2014/02/12 Javascript
在JavaScript中处理字符串之fontcolor()方法的使用
2015/06/08 Javascript
浅谈js中的in-for循环
2016/06/28 Javascript
Angular2从搭建环境到开发步骤详解
2016/10/17 Javascript
Bootstrap CSS组件之面包屑导航(breadcrumb)
2016/12/17 Javascript
Angular的自定义指令以及实例
2016/12/26 Javascript
JS实现自定义状态栏动画文字效果示例
2017/10/12 Javascript
iView-admin 动态路由问题的解决方法
2018/10/03 Javascript
angularJs select绑定的model取不到值的解决方法
2018/10/08 Javascript
浅谈Vue中render中的h箭头函数
2019/11/07 Javascript
Postman动态获取返回值过程详解
2020/06/30 Javascript
Vue实现鼠标经过文字显示悬浮框效果的示例代码
2020/10/14 Javascript
Python SQLite3数据库操作类分享
2014/06/10 Python
Python中用于去除空格的三个函数的使用小结
2015/04/07 Python
python输出当前目录下index.html文件路径的方法
2015/04/28 Python
Python多线程、异步+多进程爬虫实现代码
2016/02/17 Python
Pycharm2017版本设置启动时默认自动打开项目的方法
2018/10/29 Python
对numpy中数组转置的求解以及向量内积计算方法
2018/10/31 Python
Python3.0中普通方法、类方法和静态方法的比较
2019/05/03 Python
Python如何给你的程序做性能测试
2020/07/29 Python
Python自动化办公Excel模块openpyxl原理及用法解析
2020/11/05 Python
CSS3中的Transition过度与Animation动画属性使用要点
2016/05/20 HTML / CSS
英国奢侈品牌时尚购物平台:Farfetch(支持中文)
2020/02/18 全球购物
应聘医学检验人员自荐信
2013/09/27 职场文书
商务考察邀请函范文
2014/01/21 职场文书
《愚公移山》教学反思
2014/02/20 职场文书
公开服务承诺制度
2014/03/26 职场文书
2014年卫生工作总结
2014/11/27 职场文书
违反纪律检讨书范文
2015/05/07 职场文书
Python答题卡识别并给出分数的实现代码
2021/06/22 Python
postgreSQL数据库基础知识介绍
2022/04/12 PostgreSQL