python检测文件夹变化,并拷贝有更新的文件到对应目录的方法


Posted in Python onOctober 17, 2018

检测文件夹,拷贝有更新的文件到对应目录 2016.5.19

亲测可用,若有借鉴请修改下文件路径;

学习python小一个月后写的这个功能,属于初学,若有大神路过,求代码优化~

newcopy.py:

检测文件夹中最后修改时间变化的文件,并拷贝复制到相应路径下,拷贝目录会自动检测后输出;测试文件夹路径记得修改;

pyinotify.py:

借用window接口,检测脚本所在目录下文件夹变化(更新、删除、添加等),输出日志到桌面上;

# newcopy.py文件
# -*- coding:UTF-8 -*-
import os
import os.path
import sys
import time
import datetime
import stat
import difflib
import linecache, shutil

# 文件全路径和对应最后修改时间写入到out.txt文档中;
def add_log(path):
 with open('out.txt','w') as f:
  f.close()
 for root , dirs, files in os.walk(path):
  for name in files:
   temp_path = os.path.join(root,name)
   file_name = temp_path.replace('C:/Users/Enter/Desktop/', '')
   file_time = os.stat(temp_path).st_mtime
   with open('out.txt','a') as f:
    f.write( ','.join( ['%s' % file_name , '%s\n' % file_time] ) )
    f.close()

 # 注意时间格式转换
   #file_time = time.localtime(os.stat(root).st_mtime)
   #file_time=date.strftime('%Y-%m-%d %H:%M:%S')

def if_exist():

 # 判断文件out.txt是否存在,不存在则创建
 filename = 'out.txt'
 if os.path.exists(filename):
  message = 'OK, the "%s" file exists.'
 else:
  message = "Sorry, I cannot find the '%s' file..and I create it."
  a = open('out.txt', 'w')
  a.close()
 print message % filename

 # 判断update文件夹是否存在,不存在则创建
 files_name='update'
 if os.path.exists(files_name):
  message = 'OK, the "%s" file exists.'
 else:
  message = "Sorry, I cannot find the '%s' file.and I create it. "
  os.mkdir('update')
 print message % files_name


# path 待比较的文件夹路径
# 返回生成的txt(包含更新或者添加的文件路径)的路径
def log_compare(path):

 # 先确保out.txt存在
 if_exist()

 # 获取out.txt文件内容(文件全路径key和最后修改时间value),生成dict
 txt = open('out.txt', 'r').readlines()
 myDic = {}
 for row in txt:
  (key, value) = row.split(',')
  myDic[key] = value
 print myDic

 # 创建以时间命名的文件和文件夹
 setup_filename = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S'))    # 获取当前时间
 setup_file_path = '%s%s.txt' %('C:/Users/Enter/Desktop/update/' ,setup_filename) # 生成以当前时间命名的.txt文件,准备写入更新日志
 setup_file_dir = '%s%s' %('C:/Users/Enter/Desktop/update/' ,setup_filename)  # 生成以当前时间命名的.txt文件夹

 #判断key,比较value值是否变化
 #原始需要有一个out.txt文件,才能比较value确定是否有更新
 #运行程序时,重新遍历一遍文件全路径和最后修改时间
 for root , dirs, files in os.walk(path):
  for name in files:
   temp_path = os.path.join(root,name)
   file_name = temp_path.replace('C:/Users/Enter/Desktop/', '')
   time = os.stat(temp_path).st_mtime        # 获取最后修改时间
   file_time = '%s\n' % time          # 加%s\n是为了与out.txt里值完全对应
   if myDic.has_key(file_name) == True:
    if cmp(myDic[file_name], file_time):  # myDic[file_name]旧最后修改时间,file_time新最后修改时间
     print (file_name,file_time)    # 输出有变化的文件名及其对应的最后修改时间

     # 输出以文件时间命名的更新日志,生成路径是update下
     with open(setup_file_path,'a') as f: # 有更新的文件,写入更新日志
      f.write( '%s\n' % file_name )
      f.close()
   else:
    print "add",file_name
    with open(setup_file_path,'a') as f:   # 新增的文件,写入更新日志
      f.write( '%s\n' % file_name )
      f.close()

  # 返回 当前时间,以时间命名的文件夹路径,更新文件路径
 return (setup_filename, setup_file_dir, setup_file_path)

# 将src目录中的内容拷贝到dest目录
# 如果dest或者其子目录不存在,先创建
# txt_path为更新日志路径,有更新的文件才拷贝
def copy_directory(src, dest, txt_path):
 if not os.path.exists(txt_path):
  print "no file update"
  return

 # 读更新日志,获取更新文件的全路径

 txt = open(txt_path, 'r').readlines()
 myDic = {}
 myDic2 = {}
 for row in txt:
  myDic[row] = "1"
  tempArray = os.path.split(row)
  key = tempArray[0]
  myDic2[key] = "1"

 print "myDic2:", myDic2
 print "dict:", myDic

 # 遍历原始文件夹,得到所有文件的全路径
 for root, dirs, files in os.walk(src):
  for name in files:
   #print "dirs:",dirs
   fpath = os.path.join(root, name)
   newroot = root
   newroot = newroot.replace(src, dest)  # 根据文件绝对路径,创建将要拷贝的路径(相对路径),没有则创建
   #print newroot
   rel_dir = root.replace('C:/Users/Enter/Desktop/', '')
   if not os.path.exists(newroot) and myDic2.has_key(rel_dir):
    print "rel_dir:" , rel_dir
    print newroot
    os.makedirs(newroot)
    os.chmod(newroot, stat.S_IWRITE)
   temp = fpath
   temp = temp.replace(src, dest)
   rel_path = fpath.replace('C:/Users/Enter/Desktop/', '')  # 将绝对路径改为相对路径,便于遍历对比,挑出要拷贝的文件
   rel_path += '\n'

   if myDic.has_key(rel_path) == True:
    print "real_path:" , rel_path
    # os.mkdir(rel_path)
    shutil.copy(fpath, temp)
    print "copyfile:", fpath


def main():

 path_dir = 'C:/Users/Enter/Desktop/acd'
 path_file = 'C:/Users/Enter/Desktop/out.txt'

 params = log_compare(path_dir)
 add_log(path_dir)
 copy_directory(path_dir, params[1], params[2])


if __name__ == '__main__':
 main()
#pyinotify.py文件
# -*- coding:UTF-8 -*-
import os
import win32file
import win32con
# #检测当前目录下所有文件删除、更新、修改等变化。更新日志输出到桌面。2016.5.23 copy


ACTIONS = {
 1 : "Created",
 2 : "Deleted",
 3 : "Updated",
 4 : "Renamed from something",
 5 : "Renamed to something"
}
# Thanks to Claudio Grondi for the correct set of numbers
FILE_LIST_DIRECTORY = 0x0001
path_to_watch = "."
hDir = win32file.CreateFile (
 path_to_watch,
 FILE_LIST_DIRECTORY,
 win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
 None,
 win32con.OPEN_EXISTING,
 win32con.FILE_FLAG_BACKUP_SEMANTICS,
 None
)
while 1:
 #
 # ReadDirectoryChangesW takes a previously-created
 # handle to a directory, a buffer size for results,
 # a flag to indicate whether to watch subtrees and
 # a filter of what changes to notify.
 #
 # NB Tim Juchcinski reports that he needed to up
 # the buffer size to be sure of picking up all
 # events when a large number of files were
 # deleted at once.
 #
 results = win32file.ReadDirectoryChangesW (
 hDir,
 1024,
 True,
  win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
  win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
  win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
  win32con.FILE_NOTIFY_CHANGE_SIZE |
  win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
  win32con.FILE_NOTIFY_CHANGE_SECURITY,
 None,
 None
 )

 #print "results:", results

 for action, file in results:
 full_filename = os.path.join (path_to_watch, file)
 print full_filename, ACTIONS.get (action, "Unknown")
 with open('C:/Users/Enter/Desktop/fileupdate.txt','a') as f:
  #str = ','.join( ['%s' % full_filename , '%s\n' % ACTIONS.get (action, "Unknown")] )
  #print str
  f.write( ','.join( ['%s' % full_filename , '%s\n' % ACTIONS.get (action, "Unknown")] ) )
  f.close()

以上这篇python检测文件夹变化,并拷贝有更新的文件到对应目录的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
使用Python中的线程进行网络编程的入门教程
Apr 15 Python
Python的装饰器模式与面向切面编程详解
Jun 21 Python
Python实现的基数排序算法原理与用法实例分析
Nov 23 Python
Python进程间通信Queue实例解析
Jan 25 Python
使用Python画股票的K线图的方法步骤
Jun 28 Python
python多线程同步实例教程
Aug 11 Python
解决Atom安装Hydrogen无法运行python3的问题
Aug 28 Python
Python计算两个矩形重合面积代码实例
Sep 16 Python
利用Pytorch实现简单的线性回归算法
Jan 15 Python
深入了解NumPy 高级索引
Jul 24 Python
python实现取余操作的简单实例
Aug 16 Python
python通用数据库操作工具 pydbclib的使用简介
Dec 21 Python
python按时间排序目录下的文件实现方法
Oct 17 #Python
python3 读取Excel表格中的数据
Oct 16 #Python
python在html中插入简单的代码并加上时间戳的方法
Oct 16 #Python
Python对切片命名的实现方法
Oct 16 #Python
Python 给某个文件名添加时间戳的方法
Oct 16 #Python
解决python os.mkdir创建目录失败的问题
Oct 16 #Python
python连接mongodb密码认证实例
Oct 16 #Python
You might like
基于PHP的cURL快速入门教程 (小偷采集程序)
2011/06/02 PHP
yii2 页面底部加载css和js的技巧
2016/04/21 PHP
PHP的curl函数的用法总结
2019/02/14 PHP
PHP Swoole异步MySQL客户端实现方法示例
2019/10/24 PHP
php经典趣味算法实例代码
2020/01/21 PHP
你需要知道的10个最佳javascript开发实践小结
2012/04/15 Javascript
jquery1.10给新增元素绑定事件的方法
2014/03/06 Javascript
jquery 中的each()跳出循环的语句
2014/05/23 Javascript
javascript解析xml实现省市县三级联动的方法
2015/07/25 Javascript
jQuery遮罩层效果实例分析
2016/01/14 Javascript
深入解析Backbone.js框架的依赖库Underscore.js的作用
2016/05/07 Javascript
Bootstrap基本样式学习笔记之表格(2)
2016/12/07 Javascript
Bootstrap输入框组件使用详解
2017/06/09 Javascript
JS实现上传图片的三种方法并实现预览图片功能
2017/07/14 Javascript
nodejs中express入门和基础知识点学习
2018/09/13 NodeJs
vue集成百度UEditor富文本编辑器使用教程
2018/09/21 Javascript
javascript中关于类型判断的一些疑惑小结
2018/10/14 Javascript
vue favicon设置以及动态修改favicon的方法
2018/12/21 Javascript
Vue搭建后台系统需要注意的问题
2019/11/08 Javascript
Vue脚手架编写试卷页面功能
2020/03/17 Javascript
基于element-ui对话框el-dialog初始化的校验问题解决
2020/09/11 Javascript
如何在Vue项目中添加接口监听遮罩
2021/01/25 Vue.js
Python多线程、异步+多进程爬虫实现代码
2016/02/17 Python
浅谈scrapy 的基本命令介绍
2017/06/13 Python
Python实现的FTP通信客户端与服务器端功能示例
2018/03/28 Python
对Python模块导入时全局变量__all__的作用详解
2019/01/11 Python
Pycharm 2019 破解激活方法图文详解
2019/10/11 Python
Python Web静态服务器非堵塞模式实现方法示例
2019/11/21 Python
pyinstaller打包成无控制台程序时运行出错(与popen冲突的解决方法)
2020/04/15 Python
Giuseppe Zanotti美国官方网站:将鞋履视为高级时装般精心制作
2018/02/06 全球购物
如何用Java判断一个文件或目录是否存在
2012/11/19 面试题
社区十八大感言
2014/01/19 职场文书
教师民族团结演讲稿
2014/08/27 职场文书
工程项目经理岗位职责
2015/02/02 职场文书
个人承诺书格式范文
2015/04/29 职场文书
青年志愿者活动感想
2015/08/07 职场文书