importos,hashlib
defgetlistdir(path):
try:#如果path是一个文件的完整名称,os.listdir会抛出错误
fl=os.listdir(path)
exceptExceptionase:
fl=[]
finally:
returnfl
defgetallfile(path):
allfile=[]
fl=getlistdir(path)
iflen(fl)!=0:
fl=list(map(lambdax:path+'\'+x,fl))
allfile=allfile+fl
forfinfl:
allfile=allfile+getallfile(f)
returnallfile
defmakemd5(stri):
md5=hashlib.md5()
md5.update(stri.encode('utf-8'))
returnmd5.hexdigest()
defmain():
myfilelist=getallfile('.')#获取当前文件'.'中的所有文件和文件夹名list
myfilestr='|'.join(myfilelist)#文件list转换为以'|'分隔的字符串
print(myfilestr)#显示要进行md5摘要加密的字符
print("md5=",makemd5(myfilestr))#计算并显示md5码
main()
2. 用python3 计算指定目录下所有文件md5值,并输出到一个txt文件
import os
import hashlib
path = '指定目录'
def calc_md5(file_obj):
md5 = hashlib.md5()
while True:
chunk = file_obj.read(1024**2) # 1K
if not chunk:
return md5.hexdigest()
md5.update(chunk)
if __name__ == '__main__':
# 只遍历本目录,不遍历子目录
with open('md5.txt', 'w') as fout:
for file_name in os.listdir(path):
file_path = os.path.join(path, file_name)
if os.path.isfile(file_path):
with open(file_path, 'rb') as fin:
info = '%s %s' % (file_name, calc_md5(fin))
print(info)
fout.write(info + '\n')