如何仅复制已存在的目标文件上已更改的文件内容?

How to copy only the changed file-contents on the already existed destination file?

我有一个脚本,用于从一个位置复制到另一个位置,目录结构下的文件都是 .txt 个文件。

此脚本仅评估源上的文件大小,并且仅在文件大小不为零字节时才进行复制。但是,我需要 运行 这个脚本在 cron 一定的时间间隔后复制任何增加的数据。

所以,我需要知道如何只复制在源文件上更新的文件内容,然后只为新内容更新目标,而不仅仅是覆盖目标中已经存在的内容。

代码:

#!/bin/python3
import os
import glob
import shutil
import datetime

def Copy_Logs():
    Info_month = datetime.datetime.now().strftime("%B")
    # The result of the below glob _is_ a full path
    for filename in glob.glob("/data1/logs/{0}/*/*.txt".format(Info_month)):
        if os.path.getsize(filename) > 0:
            if not os.path.exists("/data2/logs/" + os.path.basename(filename)):
                shutil.copy(filename, "/data2/logs/")

if __name__ == '__main__':
    Copy_Logs()

我正在寻找是否有办法以 rsync 的方式使用 shutil(),或者是否有替代我的代码的方法。

简而言之,我只需要复制尚未复制的文件,然后仅在源更新时复制增量。

注意: Info_month = datetime.datetime.now().strftime("%B") 是强制保留的,因为它根据月份名称确定当前目录。

编辑:

如果我们可以使用 filecmpshutil.copyfile 模块来比较文件和目录,只是有另一个原始想法,但我不知道如何将其放入代码中。

import os
import glob
import filecmp
import shutil
import datetime

def Copy_Logs():
    Info_month = datetime.datetime.now().strftime("%B")
    for filename in glob.glob("/data1/logs/{0}/*/*.txt".format(Info_month)):
        if os.path.getsize(filename) > 0:
            if not os.path.exists("/data2/logs/" + os.path.basename(filename)) or not filecmp.cmp("/data2/logs/" + os.path.basename(filename), "/data2/logs/"):
                shutil.copyfile(filename, "/data2/logs/")

if __name__ == '__main__':
    Copy_Logs()

你要集成一个数据库,你可以根据大小、名称和作者来记录文件。

如果有任何更新,文件大小会发生变化,您可以相应地更新或追加

您需要将更改保存在某处或在文件内容更改时监听事件。对于后者,您可以使用 watchdog.

如果您决定更喜欢 cron 而不是增量检查更改(看门狗),则需要将更改存储在某个数据库中。一些基本的例子是:

ID | path        | state before cron
1  | /myfile.txt | hello
...| ...         | ...

然后检查 diff you'd dump the state before cron to a file, run a simple diff old.txt new.txt and if there is some output (i.e. there is a change), you would copy either the whole file or just the output of the diff alone which you would then apply as a patch 到您要覆盖的文件。

如果没有 diff 输出,则没有更改,因此文件中没有任何内容要更新。

编辑: 实际上 :D 如果文件在同一台机器上,您甚至可能不需要数据库...这样您就可以直接在旧版本之间进行 diff+patch和新文件。

示例:

$ echo 'hello' > old.txt && echo 'hello' > new.txt
$ diff old.txt new.txt                             # empty
$ echo 'how are you' >> new.txt                    # your file changed
$ diff old.txt new.txt > my.patch && cat my.patch  # diff is not empty now
1a2
> how are you

$ patch old.txt < my.patch  # apply the changes to the old file

并在 Python 中具有相同的 old.txtnew.txt 基数:

from subprocess import Popen, PIPE
diff = Popen(['diff', 'old.txt', 'new.txt']).communicate()[0]
Popen(['patch', 'old.txt'], stdin=PIPE).communicate(input=diff)

一种方法是将单行保存到一个文件中,以跟踪您复制文件的最新时间(在 os.path.getctime 的帮助下)并在每次复制时维护该行。

注意:以下代码段可以优化。

import datetime
import glob
import os
import shutil

Info_month = datetime.datetime.now().strftime("%B")
list_of_files = sorted(glob.iglob("/data1/logs/{0}/*/*.txt".format(Info_month)), key=os.path.getctime, reverse=True)
if not os.path.exists("track_modifications.txt"):
    latest_file_modified_time = os.path.getctime(list_of_files[0])
    for filename in list_of_files:
            shutil.copy(filename, "/data2/logs/")
    with open('track_modifications.txt', 'w') as the_file:
        the_file.write(str(latest_file_modified_time))
else:
    with open('track_modifications.txt', 'r') as the_file:
        latest_file_modified_time = the_file.readline()
    should_copy_files = [filename for filename in list_of_files if
                         os.path.getctime(filename) > float(latest_file_modified_time)]
    for filename in should_copy_files:
            shutil.copy(filename, "/data2/logs/")

方法是,创建一个文件,其中包含系统修改的最新文件的时间戳。

正在检索所有文件并按修改时间排序

list_of_files = sorted(glob.iglob('directory/*.txt'), key=os.path.getctime, reverse=True)

最初,在if not os.path.exists("track_modifications.txt"):我检查这个文件是否不存在(即第一次复制),然后我在

保存最大的文件时间戳
latest_file_modified_time = os.path.getctime(list_of_files[0])

我只是复制所有给定的文件并将此时间戳写入 track_modifications 文件。

否则,该文件存在(即,之前有文件被复制),我只是去读取那个时间戳并将它与我在 list_of_files 中读取的文件列表进行比较,并检索具有更大时间戳的所有文件(即,在我复制的最后一个文件之后创建)。那是在

should_copy_files = [filename for filename in list_of_files if os.path.getctime(filename) > float(latest_file_modified_time)]

实际上,跟踪最新修改文件的时间戳还可以让您在复制已复制的文件时获得优势当它们被更改时 :)

您可以使用 Google's Diff Match Patch (you can install it with pip install diff-match-patch) to create a diff 并从中应用补丁:

import diff_match_patch as dmp_module

#...
if not os.path.exists("/data2/logs/" + os.path.basename(filename)):
    shutil.copy(filename, "/data2/logs/")
else:
    with open(filename) as src, open("/data2/logs/" + os.path.basename(filename),
                                                                        'r+') as dst:
        dmp = dmp_module.diff_match_patch()

        src_text = src.read()
        dst_text = dst.read()

        diff = dmp.diff_main(dst_text, src_text)

        if len(diff) == 1 and diff[0][0] == 0:
            # No changes
            continue

        #make patch
        patch = dmp.patch_make(dst_text, diff)
        #apply it
        result = dmp.patch_apply(patch, dst_text)

        #write
        dst.seek(0)
        dst.write(result[0])
        dst.truncate()

这个帖子中有一些非常有趣的想法,但我会尝试提出一些新的想法。

想法没有。 1:跟踪更新的更好方法

根据你的问题,很明显你正在使用 cron 作业来跟踪更新的文件。

如果您正在尝试监控相对少量的 files/directories,我建议采用一种不同的方法来简化您的生活。

您可以使用 Linux inotify 机制,它允许您监视特定的 files/directories 并在写入文件时得到通知。

Pro:您立即知道每一次写入,无需检查更改。您当然可以编写一个处理程序,它不会为每次写入更新目标,而是在 X 分钟内更新一次。

这是一个使用 inotify python 包的例子(取自 package's page):

import inotify.adapters

def _main():
    i = inotify.adapters.Inotify()

    i.add_watch('/tmp')

    with open('/tmp/test_file', 'w'):
        pass

    for event in i.event_gen(yield_nones=False):
        (_, type_names, path, filename) = event

        print("PATH=[{}] FILENAME=[{}] EVENT_TYPES={}".format(
              path, filename, type_names))

if __name__ == '__main__':
    _main()

想法没有。 2:仅复制更改

如果您决定使用 inotify 机制,跟踪您的状态将变得微不足道。

那么,有两种可能:

1.始终附加新内容

如果是这种情况,您可以简单地复制从最后一个偏移量到文件末尾的任何内容。

2。新内容随机写入

在这种情况下,我也会推荐其他答案提出的方法:使用差异补丁。在我看来,这是迄今为止最优雅的解决方案。

这里的一些选项是:

rsync 的一个好处是它只复制文件之间的差异。随着文件变大,它会大大减少 I/O.

在 PyPI 中围绕原始程序有大量类似 rsync 的实现和包装器。这个blog post很好的描述了如何在Python中实现rsync,可以直接使用。

至于检查是否需要同步,可以使用filecmp.cmp()。在它的浅变体中,它只检查 os.stat() 签名。

如前所述,rsync 是执行此类工作的更好方法,您需要执行增量文件列表或说数据增量所以,我宁愿使用 rsync 和 subprocess 模块一直。

但是,您也可以根据需要分配一个变量 Curr_date_month 来获取当前日期、月份和年份,以便仅从当前月份和日期文件夹中复制文件。您也可以定义源变量和目标变量,以便于将它们写入代码。

其次,虽然您使用 getsize 检查文件大小,但我想添加一个 rsync 选项参数 --min-size= 以确保不复制零字节文件。

你的最终代码在这里。

#!/bin/python3
import os
import glob
import datetime
import subprocess

def Copy_Logs():
    # Variable Declaration to get the month and Curr_date_month
    Info_month = datetime.datetime.now().strftime("%B")
    Curr_date_month = datetime.datetime.now().strftime("%b_%d_%y") 
    Sourcedir = "/data1/logs"
    Destdir = "/data2/logs/"
    ###### End of your variable section #######################
    # The result of the below glob _is_ a full path
    for filename in glob.glob("{2}/{0}/{1}/*.txt".format(Info_month, Curr_date_month, Sourcedir)):
        if os.path.getsize(filename) > 0:
            if not os.path.exists(Destdir + os.path.basename(filename)):
                subprocess.call(['rsync', '-avz', '--min-size=1', filename, Destdir ])

if __name__ == '__main__':
    Copy_Logs()