原文地址(http://www.360doc.com/content/22/0703/00/18334519_1038381318.shtml)
import os
import sys
import filecmp
import shutil
holderlist=[]
# 对比两个文件差异
# @params dir1 文件1
# @params dir2 文件2
def compareme(dir1,dir2):
dircomp = filecmp.dircmp(dir1,dir2)
only_in_one = dircomp.left_only
diff_in_one = dircomp.diff_files
dirpath = os.path.abspath(dir1)
[holderlist.append(os.path.abspath(os.path.join(dir1,x))) for x in only_in_one]
[holderlist.append(os.path.abspath(os.path.join(dir1,x))) for x in diff_in_one]
if len(dircomp.common_dirs) > 0:
for item in dircomp.common_dirs:
compareme(os.path.abspath(os.path.join(dir1,item)), os.path.abspath(os.path.join(dir2,item)))
return holderlist
# 主程序
def main():
# 从命令中读取两个参数
if len(sys.argv) > 2:
dir1 = sys.argv[1] # 数据文件夹
dir2 = sys.argv[2] # 目标文件夹
else:
print("请准确输入参数,例如:python comp.py datadir backupdir")
sys.exit()
source_files = compareme(dir1,dir2)
dir1 = os.path.abspath(dir1)
if not dir2.endswith('/'):
dir2 = dir2+'/'
dir2 = os.path.abspath(dir2)
destination_files = []
createdir_bool = False
for item in source_files:
destination_dir = item.replace(dir1, dir2)
destination_files.append(destination_dir)
if os.path.isdir(item):
if not os.path.exists(destination_dir):
os.makedirs(destination_dir)
createdir_bool = True
if createdir_bool:
destination_files = []
source_files = []
source_files = compareme(dir1,dir2)
for item in source_files:
destination_dir = item.replace(dir1, dir2)
destination_files.append(destination_dir)
print("更新的内容:")
print(source_files)
copy_pair = zip(source_files,destination_files)
for item in copy_pair:
if os.path.isfile(item[0]):
shutil.copyfile(item[0],item[1])
if __name__ == '__main__':
main()