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')
追问能不能给个缩进?这样对不对?运行不起来
![](https://video.ask-data.xyz/img.php?b=https://iknow-pic.cdn.bcebos.com/7c1ed21b0ef41bd5dece892e5fda81cb38db3d4e?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_600%2Ch_800%2Climit_1%2Fquality%2Cq_85%2Fformat%2Cf_auto)
追答![](https://video.ask-data.xyz/img.php?b=https://iknow-pic.cdn.bcebos.com/b7fd5266d0160924d1ecc1c1da0735fae7cd341a?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_600%2Ch_800%2Climit_1%2Fquality%2Cq_85%2Fformat%2Cf_auto)