需求:针对某个目录下的大文件,输出md5值,因文件较多,结果需保存在文件中。
python版本 2.7.6
参考:
主要引用:http://blog.csdn.net/werm520/article/details/7337007
遍历目录:http://zhidao.baidu.com/link?url=hEQzMfLZqHTZdysYHEgL-osaSVlRwL4z5NhD-xuKt8Q9rKm3f3GkBXyNOv7cex5CevVqpQJ_At1sahrfcj4df_
结果保存文件:http://bbs.sjtu.edu.cn/bbstcon,board,Script,reid,1277103283,file,M.1277103283.A.html
未引用该处代码:http://www.oschina.net/code/snippet_85544_2805
------md5sum.py
import hashlib
import os
import subprocess
from optparse import OptionParser
def fun(path):
result = []
for path,subdirs,files in os.walk(path):
for name in files:
result.append(os.path.join(path,name))
return result
#调用了linux自带工具md5sum
#指定目录/home/pysrc
for sfile in fun('/home/pysrc'):
if not sfile.endswith('.md5'):
subprocess.call(['md5sum',sfile])
else:
subprocess.call(['cat',sfile])
#大文件生成md5
def GetFileMd5(filename):
if not os.path.isfile(filename):
return
myhash = hashlib.md5()
f = file(filename,'rb')
while True:
b = f.read(8096)
if not b :
break
myhash.update(b)
f.close()
return myhash.hexdigest()
#保存到文件
for sfile in fun('/mnt/sdc'):
data = os.path.basename(sfile) +" "+str(GetFileMd5(sfile)) //当输出getfilemd5输出none时,会报错。使用str 可修复
fp = open('sdc_md5.txt','a') //a是添加到文件,w写入【会只保留当前结果,上一条记录会被冲掉】
fp.write(data)
fp.write('\n')
fp.close
-------------------
linux 执行时,保存到文件也可如下方式
python md5sum.py 1>log.txt 2>&1 //将结果保存在log.txt中。