利用python校验源与备份目录差异,同步。

#!/usr/bin/python
#--*--encoding=utf8--*--
import filecmp,os,re,shutil,sys
def Z_xunhuan(src,dst):
	dir1=os.path.abspath(src)
	dir2=os.path.abspath(dst)
	x=filecmp.dircmp(dir1,dir2)	
	left_only=x.left_only
	diff_files=x.diff_files
	comm_dir=x.common_dirs
		
	if left_only:
		for i in left_only:						#左边有的,判断是文件还是目录,然后进行复制
			new_src=os.path.join(dir1,i)
			new_dst=dir2+'/'+i
			asum.append(new_src)			
			if os.path.isdir(new_src):
				shutil.copytree(new_src,new_dst)
			else:
				shutil.copy(new_src,dir2)
				
	if diff_files:								#不同的文件,直接复制
		for i in diff_files:
			new_src=os.path.join(dir1,i)
			asum.append(new_src)
			shutil.copy(new_src,dir2)
			
	if comm_dir:
		for i in comm_dir:						#相同目录的,进入自循环调用函数执行动作
			new_src=os.path.join(dir1,i)
			new_dst=os.path.join(dir2,i)
			Z_xunhuan(new_src,new_dst)
			
def N_xunhuan(src,dst):							#逆向对比的反之亦然,多了的删去
	dir1=os.path.abspath(src)
	dir2=os.path.abspath(dst)	
	x=filecmp.dircmp(dir1,dir2)	
	left_only=x.left_only
	diff_files=x.diff_files
	comm_dir=x.common_dirs
	
	if left_only:
		for i in left_only:
			new_src=os.path.join(dir1,i)
			info=re.sub(src,dst,new_src)
			dsum.append(info)
			if os.path.isdir(new_src):
				shutil.rmtree(new_src)
			else:
				os.remove(new_src)
			
	if comm_dir:
		for i in comm_dir:
			new_src=os.path.join(dir1,i)
			new_dst=os.path.join(dir2,i)
			N_xunhuan(new_src,new_dst)
			
def main():		
	if len(sys.argv) == 3:
		src=sys.argv[1]
		dst=sys.argv[2]
	else:
		print "Usage python %s src_dir dst_dir" % sys.argv[0]
		sys.exit(10)		
	global asum,dsum	
	asum=[]
	Z_xunhuan(src,dst)
	print 'add: ',asum
	dsum=[]
	N_xunhuan(dst,src)
	print 'del: ',dsum
		
if __name__ == '__main__': main()
			

运行结果如下:最后部分显示已经没内容更新了,上面的就是更新或删除的内容

利用python校验源与备份目录差异,同步。_第1张图片

你可能感兴趣的:(利用python校验源与备份目录差异,同步。)