清风竹林

ぷ雪飘绛梅映残红
   ぷ花舞霜飞映苍松
     ----- Do more,suffer less

目录文件比较工具 python

  用于目录文件的比较,如果有文件的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)
        




posted on 2009-05-04 18:15 李现民 阅读(704) 评论(0)  编辑 收藏 引用 所属分类: minitools


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理