用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')追问

能不能给个缩进?这样对不对?运行不起来

追答

温馨提示:答案为网友推荐,仅供参考
相似回答