用于目录文件的比较,如果有文件的md5值不一样, 则copy覆盖。由于写的很久匆忙,没有加注释,但好在代码很少,如下:
import sys, os, shutil
import hashlib
class FileHash(object):
def __hash_file(self, filepath):
if os.path.exists(filepath):
m= hashlib.md5()
with open(filepath, 'rb') as fin:
while True:
data= fin.read(8096)
if not data:
break
m.update(data)
return m.hexdigest()
def compare_file(self, srcfile, destfile):
src_md5= self.__hash_file(srcfile)
dest_md5= self.__hash_file(destfile)
isOk= (src_md5==dest_md5)
return isOk
if __name__ == '__main__':
file_hash= FileHash()
srcdir =r'E:\game'
destdir =r'C:\game'
for root, dirs, files in os.walk(srcdir):
for filename in files:
src_file_path = os.path.join(root, filename)
dest_file_path = os.path.join(destdir, src_file_path[len(srcdir)+1:])
cur_dest_dir= os.path.split(dest_file_path)[0]
if not os.path.exists(cur_dest_dir):
shutil.copytree(root, cur_dest_dir)
print('created dir: %s'%cur_dest_dir)
elif not os.path.exists(dest_file_path) or not file_hash.compare_file(src_file_path, dest_file_path):
shutil.copyfile(src_file_path, dest_file_path)
print('created file: %s'%dest_file_path)