在Python中,如何仅在源文件比目标文件更新时复制文件?

在Python中,如何仅在源文件比目标文件更新时复制文件?,python,Python,我正在编写一个脚本,将编译后的文件从一个位置复制到另一个位置 我现在的情况是这样的: import os import shutil shutil.copy2 (src, dst) #... many more shutil.copy commands #src is a filename string #dst is the directory where the file is to be copied 我的问题是,许多被复制的文件都是大文件,并且不是所有的文件都在每个编译周期中重新编译

我正在编写一个脚本,将编译后的文件从一个位置复制到另一个位置

我现在的情况是这样的:

import os
import shutil

shutil.copy2 (src, dst)
#... many more shutil.copy commands
#src is a filename string
#dst is the directory where the file is to be copied

我的问题是,许多被复制的文件都是大文件,并且不是所有的文件都在每个编译周期中重新编译。理想情况下,我只希望复制此脚本中更改的文件。我有什么办法可以做到这一点吗

您可以尝试一下rsync的python实现


如果文件修改时间足够,您可以利用文件修改时间:

# If more than 1 second difference
if os.stat(src).st_mtime - os.stat(dest).st_mtime > 1:
    shutil.copy2 (src, dst)

或者调用rsync之类的同步工具。

如果您没有明确的理由需要自己用python编写代码,我建议您使用rsync。从其手册页:

Rsync是一种速度非常快的 多功能文件复制工具。它是 以三角洲转移而闻名 算法,它减少了 通过发送通过网络发送的数据 只有 源文件和中的现有文件 目的地

但是,如果您确实希望用Python编写此代码,那么首先应该学习
您希望如何查找已更改的文件?您可以在src上使用os.path.getmtime(path)并检查它是否比某些存储的时间戳(例如上次复制的时间戳)更新,或者使用filecmp.cmp(f1,f2[,shall])检查文件是否更新

注意使用filecmp.cmp,您还复制了统计数据(copy2),因此您必须检查浅对比是否适合您。

来自AndiDog的回答:

os.stat(dst).st_mtime - os.stat(src).st_mtime
如果“src”文件较新,则为负值,因此应为:

if os.stat(src).st_mtime - os.stat(dst).st_mtime > 1:

您可以通过设置可选参数来执行智能复制:
update=1

还有一个版本使用
distutils.dir\u util.copy\u tree
复制整个目录

然后,您可以验证其中一个是否实际工作,并且仅复制所需的文件:


它将打印复制的文件。

要基于AndiDog的答案,如果目标文件夹中可能不存在文件,请执行以下操作:

# copy file if destination is older by more than a second, or does not exist
if (not os.path.exists(dest)) or (os.stat(src).st_mtime - os.stat(dest).st_mtime > 1) :
    shutil.copy2 (src, dest)

为什么
>1
-不应该是
>0
?我想这取决于用例。如果文件总是使用
shutil.copy2
编写,那么修改时间可以完全相等(那么它就是
>0
)。rsync的速度可能慢得离谱。。。将我的整个8TB硬盘复制到新硬盘需要一周多的时间。更新为1的Python distutils.dir\u util.copy\u树要快得多。。。大约快5-6倍。
# copy file if destination is older by more than a second, or does not exist
if (not os.path.exists(dest)) or (os.stat(src).st_mtime - os.stat(dest).st_mtime > 1) :
    shutil.copy2 (src, dest)