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爬虫之urllib2使用指南
Nov 05 Python
python实现kNN算法
Dec 20 Python
学习python中matplotlib绘图设置坐标轴刻度、文本
Feb 07 Python
Python直接赋值、浅拷贝与深度拷贝实例分析
Jun 18 Python
django的csrf实现过程详解
Jul 26 Python
python3 sleep 延时秒 毫秒实例
May 04 Python
Python使用Excel将数据写入多个sheet
May 16 Python
如何把外网python虚拟环境迁移到内网
May 18 Python
python爬虫基础知识点整理
Jun 02 Python
Python 基于jwt实现认证机制流程解析
Jun 22 Python
Keras中 ImageDataGenerator函数的参数用法
Jul 03 Python
Python3 pyecharts生成Html文件柱状图及折线图代码实例
Sep 29 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中escape与unescape的方法
2016/07/11 PHP
ThinkPHP实现生成和校验验证码功能
2017/04/28 PHP
PHP实现图片压缩
2020/09/09 PHP
FireFox中textNode分片的问题
2007/04/10 Javascript
网站导致浏览器崩溃的原因总结(多款浏览器) 推荐
2010/04/15 Javascript
最佳JS代码编写的14条技巧
2011/01/09 Javascript
浅析webpack 如何优雅的使用tree-shaking(摇树优化)
2017/08/16 Javascript
windows系统下更新nodejs版本的方案
2017/11/24 NodeJs
vue中手机号,邮箱正则验证以及60s发送验证码的实例
2018/03/16 Javascript
使用Taro实现小程序商城的购物车功能模块的实例代码
2020/06/05 Javascript
[27:02]2014 DOTA2国际邀请赛中国区预选赛 5 23 CIS VS LGD第三场
2014/05/24 DOTA
[03:08]Ti4观战指南上
2014/07/07 DOTA
python获得图片base64编码示例
2014/01/16 Python
python使用递归解决全排列数字示例
2014/02/11 Python
通过C++学习Python
2015/01/20 Python
对python3 中方法各种参数和返回值详解
2018/12/15 Python
Python3-异步进程回调函数(callback())介绍
2020/05/02 Python
Python 字节流,字符串,十六进制相互转换实例(binascii,bytes)
2020/05/11 Python
Python web如何在IIS发布应用过程解析
2020/05/27 Python
CSS3实现多背景模拟动态边框的效果
2016/11/08 HTML / CSS
html5中的input新属性range使用记录
2014/09/05 HTML / CSS
英国马莎百货官网:Marks & Spencer
2016/07/29 全球购物
澳大利亚在线家具、灯饰和家居装饰店:LivingStyles
2018/11/20 全球购物
绿化先进工作者事迹材料
2014/01/30 职场文书
升旗仪式主持词
2014/03/19 职场文书
社区领导班子四风问题原因分析及整改措施
2014/09/28 职场文书
学籍证明模板
2014/11/21 职场文书
2014年政府采购工作总结
2014/12/09 职场文书
领导干部考核评语
2015/01/04 职场文书
新闻报道稿范文
2015/07/23 职场文书
工作后的感想
2015/08/07 职场文书
2016年小学生寒假总结
2015/10/10 职场文书
python小程序之飘落的银杏
2021/04/17 Python
MySQL 8.0 Online DDL快速加列的相关总结
2021/06/02 MySQL
Python3 多线程(连接池)操作MySQL插入数据
2021/06/09 Python
python如何将mat文件转为png
2022/07/15 Python