【详细】Python检查文件更新改变功能

        很多时候我们需要检测某个文件夹下的文件变化,但是一个文件夹目录下的文件甚多,逐一检测十分麻烦,因此希望通过脚本实现自动化检测文件更新、变化情况。

        当前检测文件是否更新的办法,主要是有两类,一类是根据文件最后修改日期进行判断;还有一类是根据文件大小进行判断,如果文件大小发生了改变,那么证明文件发生了改变。为了探究那类更好实现,本文以此做了实现。

1. 判断最后修改日期

1.1 实现流程

  1. 确定检测文件的部署路径(/tmp/software)
  2. 遍历文件夹下的所有文件
  3. 判断检测文件夹下是否还有包含的文件夹
  4. 获取每个文件的最后修改日期
  5. 存入txt文件,拼接文件名filename和最后修改时间tmptime

1.2 代码演示

# -*- coding:UTF-8 -*-
# -*- create on 2019/06/28 by HangLi -*-
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/HangLi/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/HangLi/Desktop/update/', setup_filename)  # 生成以当前时间命名的.txt文件,准备写入更新日志
    setup_file_dir = '%s%s' % ('C:/UseHangLi/Desktop/update/', setup_filename)  # 生成以当前时间命名的.txt文件夹

    # 判断key,比较value值是否变化rs/
    # 原始需要有一个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/HangLi/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/HangLi/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/HangLi/Desktop/acd'
    path_file = 'C:/Users/HangLi/Desktop/out.txt'

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



if __name__ == '__main__':
    main()

注意:这里的path_file 也就是文件路径,是你要检测的文件夹的路径  C:\User\HangLi\Desktop\acd

1.3 结果显示 

运行脚本后,会生成update日志文件

日志会记录修改的文件名称

 

 2. 根据文件大小判断

       根据最后修改日期判断文件是否更新,有一定的局限性,因为有时候,当我们需要比对两个文件夹下面的文件是否一致时,两个文件夹可能在两台不同的设备上,那么他们的服务器时间假如不一样,那么最后修改时间也会不一样,会造成误差。

为此我完善了我的脚本,加入了根据文件大小进行判断文件是否修改的功能。

#  获取文件的大小,结果保留两位小数,单位为MB
def get_FileSize(filePath):
    filePath = unicode(filePath,'utf8')
    fsize = os.path.getsize(filePath)
    fsize = fsize/float(1024*1024)
    print round(fsize,2)

写了一个函数,在遍历目录文件的地方,调用该函数,可以遍历获取该目录下所有文件的大小。

可以看到对应检测文件的大小,单位为MB,后期我会优化脚本,加入更多单位的判断。

发布了51 篇原创文章 · 获赞 97 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/m0_37218227/article/details/94589997
今日推荐