首页 > 解决方案 > python: update (source newer than destination or destination missing) copy files

问题描述

Is there a ready tool in python to update copy files? "Update copy" means that a copy should only be made if the source file is newer than the destination or if the destination file is missing, i.e. equivalent of the Linux cp -u command.

I understand that I could write the code myself by checking for existence of each destination file and by checking the time-stamps of both the source and the destination files and comparing them, but I do not want to "invent the bicycle" (i.e. invent something that has already been invented a long time ago) here if such a tool already exists.

Thank you very much for your help!

标签: pythonfilecopyupdates

解决方案


distutils模块可以做到这一点。

例如,要更新 directoryb中已更改的所有文件 directory a

from distutils.dir_util import copy_tree
copy_tree("a", "b", update=1)

不是很有帮助,这将返回其中所有文件的列表,这些文件b是否a已更新(也就是说,如果文件x在两个目录中,即使它不需要更新,它也会在列表中)。

您还可以使用:

from distutils.file_util import copy_file
copy_file('src', 'dst', update=1)

这至少会返回一个有用的元组:

('dst', 1)

1指示文件已更新,否则0。(即该值是真实的,但不一定是 a bool)。


推荐阅读