python - 代码练习 - 差异备份

时间:2021-02-10 14:07:34

差异备份

import os
import filecmp
import shutil

dir1 = r"./a"
dir2 = r"./b"

def a(dir1,dir2):
    cc = []
    d1 = os.path.abspath(dir1)
    d2 = os.path.abspath(dir2)
    a1 = filecmp.dircmp(d1,d2)

    cc += a1.diff_files + a1.left_only
    print("差异列表:",cc)

    if cc:
        for i3 in cc:
            # print(os.path.join(d1,i3))
            if os.path.isfile(os.path.join(d1,i3)):
                shutil.copy2(os.path.join(d1,i3),d2)
            else:
                os.makedirs(os.path.join(d2,i3))
                a(os.path.join(d1,i3),os.path.join(d2,i3))
    else:
        a2 = a1.left_list
        for i in a2:
            if os.path.isdir(os.path.join(d1,i)):
                a(os.path.join(d1,i), os.path.join(d2,i))

a(dir1,dir2)

 

缺点:

  a目录中修改了一个文件的文件名,那么b路径中会重新创建a目录中被修改的目录.