遍历目录下的所有文件,计算文件的md5并输出


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#encoding=utf-8
#author: skybug
#date: 2014-04-23
#function: 遍历目录所有文件,计算每个文件的md5 输出到md5.txt
import  os,sys,getopt,hashlib
logfile = 'md5.txt'
limt = 8388608   #(8M)
def  listdir( dir ):
     global   logfile
     logfile  =  dir  +  os.path.sep  +  logfile
     for  files  in  os.listdir( dir ) :
         path = os.path.join( dir ,files)
         if  os.path.isdir(path):
             continue
         else :
             filepath  =  dir  +  os.path.sep  +  files
             line  =  getfilemd5(filepath)
             w_log(logfile,line)
def  getfilemd5(filepath):
     global  limt
     size  =  os.path.getsize(filepath)
     f = open (filepath, 'rb' )
     if  size <  int (limt) + 1 :
         m1 = hashlib.md5()
         m1.update(f.read(limt))
         myhash  =  m1.hexdigest().upper()
         line  =  filepath  +  ';'  +  myhash
         f.close()
         return  line
         #print 'if' + '**'+ line
     else :
         m1 = hashlib.md5()
         while  True :
             block = f.read(limt)
             if  not  block:
                 break
             m1.update(block)
         myhash  =  m1.hexdigest().upper()
         line  =  filepath  +  ';'  +  myhash
         f.close()
         return  line
def  w_log(log_file_name, line):
     try :
         log_file  =  open (log_file_name,  'a' )
         line = line + '\n'
         log_file.write(line)
     except  IOError as err:
         print ( 'File error: '  +  str (err))
     finally :
         if  'file'  in  locals ():
             log_file.close()
dir  =  raw_input ( 'please input dir:\n' )
listdir( dir )






      本文转自天山三害 51CTO博客,原文链接:http://blog.51cto.com/skybug/1401977,如需转载请自行联系原作者




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值